Skip to content

Commit f92736b

Browse files
Merge pull request #118 from Travelopia/feature/form-add-validation-for-zip
Add validation for zip code
2 parents 52ea7d1 + f9bf57e commit f92736b

File tree

3 files changed

+43
-3
lines changed

3 files changed

+43
-3
lines changed

package-lock.json

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/form/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import * as email from './validators/email';
1414
import * as minLength from './validators/min-length';
1515
import * as maxLength from './validators/max-length';
1616
import * as noEmptySpaces from './validators/no-empty-spaces';
17+
import * as zip from './validators/zip';
1718

1819
// Prepare validators.
1920
const validators = [
@@ -22,6 +23,7 @@ const validators = [
2223
minLength,
2324
maxLength,
2425
noEmptySpaces,
26+
zip,
2527
];
2628

2729
/**

src/form/validators/zip.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Internal dependencies.
3+
*/
4+
import { TPFormFieldElement } from '../tp-form-field';
5+
import { TPFormValidator } from '../definitions';
6+
import { getErrorMessage } from '../utility';
7+
8+
/**
9+
* Name.
10+
*/
11+
export const name: string = 'zip';
12+
13+
/**
14+
* Error message.
15+
*/
16+
export const errorMessage: string = 'Please enter a valid zip code';
17+
18+
/**
19+
* Validator.
20+
*/
21+
export const validator: TPFormValidator = {
22+
validate: ( field: TPFormFieldElement ): boolean => {
23+
// Get the field value or default to empty string.
24+
const value = field.getField()?.value ?? '';
25+
26+
// Get custom regex pattern from regex attribute or use default.
27+
const customPattern: string | null = field.getAttribute( 'regex' );
28+
const defaultPattern: string = '^[A-Za-z0-9][A-Za-z0-9\\- ]{1,8}[A-Za-z0-9]$';
29+
const pattern: string = customPattern ?? defaultPattern;
30+
31+
// Create regex object from pattern.
32+
const zipCodeRegex: RegExp = new RegExp( pattern );
33+
34+
// Test the trimmed value against the regex pattern.
35+
return zipCodeRegex.test( value.trim() );
36+
},
37+
getErrorMessage: (): string => getErrorMessage( name ),
38+
};

0 commit comments

Comments
 (0)