Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/form/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import * as email from './validators/email';
import * as minLength from './validators/min-length';
import * as maxLength from './validators/max-length';
import * as noEmptySpaces from './validators/no-empty-spaces';
import * as zip from './validators/zip';

// Prepare validators.
const validators = [
Expand All @@ -22,6 +23,7 @@ const validators = [
minLength,
maxLength,
noEmptySpaces,
zip,
];

/**
Expand Down
38 changes: 38 additions & 0 deletions src/form/validators/zip.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Internal dependencies.
*/
import { TPFormFieldElement } from '../tp-form-field';
import { TPFormValidator } from '../definitions';
import { getErrorMessage } from '../utility';

/**
* Name.
*/
export const name: string = 'zip';

/**
* Error message.
*/
export const errorMessage: string = 'Please enter a valid zip code';

/**
* Validator.
*/
export const validator: TPFormValidator = {
validate: ( field: TPFormFieldElement ): boolean => {
// Get the field value or default to empty string.
const value = field.getField()?.value ?? '';

// Get custom regex pattern from regex attribute or use default.
const customPattern: string | null = field.getAttribute( 'regex' );
const defaultPattern: string = '^[A-Za-z0-9][A-Za-z0-9\\- ]{1,8}[A-Za-z0-9]$';
const pattern: string = customPattern ?? defaultPattern;

// Create regex object from pattern.
const zipCodeRegex: RegExp = new RegExp( pattern );

// Test the trimmed value against the regex pattern.
return zipCodeRegex.test( value.trim() );
},
getErrorMessage: (): string => getErrorMessage( name ),
};