angular When form needs to be verified, angular comes with many validators, but often the built-in cannot meet business needs. At this time, a custom validator is needed
Define a validator
Defining validator requires implementing the ValidatorFn interface
Source code:
export interface ValidatorFn { (c: AbstractControl): ValidationErrors | null; }
Receive an AbstractControl Return ValidationErrors or null
ValidationErrors Source Code
export declare type ValidationErrors = { [key: string]: any; };
This is actually returning an object of type key value, which will be assigned to the
The written Validator needs to be passed in as a parameter when creating a FormControl
FormControl's constructor source code
export declare class FormControl extends AbstractControl { constructor(formState?: any, validator?: ValidatorFn | ValidatorFn[] | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);
Here is a simple example (check email address):
Define a method that returns the ValidatorFn interface
static EMAIL_REG = new RegExp('\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}'); static email(): ValidatorFn { return (control: AbstractControl): { [key: string]: any } => { ① if (!EMAIL_REG.test()) { ② return { ③ errMsg: 'Please enter the correct email address' }; } return {}; ④ }; }
① Method returns an instance of ValidatorFn
② Determine whether it meets the mailbox regular expression
③ If it does not match, return a ValidationErrors object, errMsg is output as error message (a boolean type can also be added here for judgment)
④ If the verification is successful, return an empty object
Incoming the checker
email = new FormControl('', email())
template:
<p *ngIf = "! && ">{{}}</p>
When the email format is incorrect, the 'Please enter the correct email address' will be displayed here.
At this point a simple verification device is completed.
If you want to compare whether the values of the two forms are equal, you only need to make some small changes.
static EMAIL_REG = new RegExp('\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}'); static email(emailForm: FormControl): ValidatorFn { ① return (control: AbstractControl): { [key: string]: any } => { if ( !== ) { return { errMsg: 'Please enter the same email address' }; } return {}; }; }
① Just pass in another formControl that needs to be compared here
email = new FormControl('', email()) email2 = new FormControl('', email(email))
The above is the implementation method of Angular2 custom validators introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!