File tree Expand file tree Collapse file tree 3 files changed +43
-3
lines changed Expand file tree Collapse file tree 3 files changed +43
-3
lines changed Original file line number Diff line number Diff line change @@ -14,6 +14,7 @@ import * as email from './validators/email';
1414import * as minLength from './validators/min-length' ;
1515import * as maxLength from './validators/max-length' ;
1616import * as noEmptySpaces from './validators/no-empty-spaces' ;
17+ import * as zip from './validators/zip' ;
1718
1819// Prepare validators.
1920const validators = [
@@ -22,6 +23,7 @@ const validators = [
2223 minLength ,
2324 maxLength ,
2425 noEmptySpaces ,
26+ zip ,
2527] ;
2628
2729/**
Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments