Implementation of Angular2 form custom validators, angular2 form

Source: Internet
Author: User
Tags export class

Implementation of Angular2 form custom validators, angular2 form

This article describes how to determine the result of the validators. Here, we will look at how to implement a custom validators.

Target

We need to implement a mobile phone number verification tool. The instance used is based on the instance in the previous article, that is, the form page of user information input. We add a cell phone number validator to the cell phone number element. If the mobile phone number verification fails, an error is displayed, as shown in the following figure:

The code for this part of the tutorial can be obtained from github:

Git clone

Https://github.com/Mavlarn/angular2-forms-tutorial

To run the command, go to the project directory, run the following command to install the dependency, and then run the test Server:

Cd angular2-forms-tutorialgit checkout model-driven # Check out the tagnpm installnpm start used in this article

Implement validators

In Angular2, it is very easy to implement a validator, that is, a method. The parameter of this method is a FormControl, and the result is an error object or null. It is represented by the TypeScript interface as follows:

interface Validator<T extends FormControl> {(c:T): {[error: string]:any};}

If you are familiar with object-oriented languages like Java, the above interface definition is easy to understand. <T extends FormControl> refers to a generic T used in this method. It is an object inherited from FormControl. (C: T): {[error: string]: any}; this is the method definition of a lambda expression. The type of parameter c is T. This method returns an object.

Create a file named mobile. validator. ts with the following content:

import { FormControl } from '@angular/forms';export function validateMobile(c: FormControl) {let MOBILE_REGEXP = /^1[0-9]{10,10}$/;return MOBILE_REGEXP.test(c.value) ? null : {validateMobile: {valid: false}}}

In this verification method, the type of parameter c is FormControl, that is, Form Control, which has a value attribute that stores the current value. We use a regular expression to determine whether the value is valid. If it is invalid, an object is returned.
In the previous tutorial, we obtained the verification results for the validators as follows:

<P * ngIf = "userForm. controls. mobile ?. Errors ?. Required "> you must enter the phone number </p>

UserForm. controls. mobile is the mobile phone number control in the form, and required is the key corresponding to the required validators. When the required validators fail to verify, a value will be added to errors:

{required: {valid: false}}

Therefore, the User-Defined validators we implement should also put the verification results using the name of the validators as the key and put it in errors, which is like this:

{validateMobile: {valid: false}}

In this way, we can obtain the verification result of this validator in the same way as before on the page.

Add validators to the model-driven form

Next, we add the validators we implement to our form and add them to the model-driven form first:

Import {validateMobile} from '.. /validators/mobile. validator '; export class ReactiveFormsComponent implements OnInit {this. userForm = this. formBuilder. group ({//... omit other controls mobile: [13800138001, [Validators. required, Validators. minLength (11), Validators. maxLength (11), validateMobile]});...}

The above Code omitted other parts. For the complete code, refer to github.

In the above Code, we introduced the previously implemented custom validators, and then added validateMobile to the mobile control in the Form Control creation code.

In this way, we add the corresponding verification result information on the page:

<P * ngIf = "userForm. controls. mobile. errors ?. ValidateMobile "> incorrect Phone Number Format </p>

This completes the validators and displays the verification results on the page.

Add validators to the template-driven form

However, if our forms are not created in a model-driven manner in the component, but are created on the page using html elements, it would be a little effort to use a custom validators.

In a template-driven form, we use the validators as follows:

<Input type = "text" name = "mobile" [(ngModel)] = "user. mobile "# mobile =" ngModel "required minlength =" 11 "maxlength =" 11 "> <span * ngIf =" mobile. valid "> valid </span> <div [hidden] =" mobile. valid | mobile. pristine "> <p * ngIf =" mobile. errors ?. Minlength | mobile. errors ?. Maxlength "> the telephone length must be 11 </p> <p * ngIf =" mobile. errors ?. Required "> name required </p> </div>

That is, add the validator to the attribute of the input element. Then, we need to implement our own validators to be used in the form. In addition to the above validators, two more things are required:

We need to define this validator as a Directive direve ve, so Angular will recognize our custom validator Directive when parsing this html section.
We also need Angular validators to call our verification method.
Therefore, in the previous mobile. validator. ts file, add the following command definition:

@Directive({selector: '[validateMobile][ngModel]'})export class MobileValidator {}

This code is simple. The @ Directive label is used to define a MobileValidator command. It serves elements with both validateMobile and ngModel attributes. In this way, we can add an attribute on the mobile phone number element to make this validator command take effect.
Then, we also need Angular's validator framework to call our verification method, which requires NG_VALIDATORS. We modify the validator command definition as follows:

@Directive({selector: '[validateMobile][ngModel]',providers: [{ provide: NG_VALIDATORS, useValue: validateMobile, multi: true }]})export class MobileValidator {}

In this way, Angular validators can apply the validateMobile method to this command.

Finally, add the new command to the declarations of the AppModule to use the validator on the page.

Finally, the Code for using the validators on the page is as follows:

<Input type = "text" name = "mobile" [(ngModel)] = "user. mobile "# mobile =" ngModel "required minlength =" 11 "maxlength =" 11 "validateMobile> <span * ngIf =" mobile. valid "> valid </span> <div [hidden] =" mobile. valid | mobile. pristine "> <p * ngIf =" mobile. errors ?. Minlength | mobile. errors ?. Maxlength "> the telephone length must be 11 </p> <p * ngIf =" mobile. errors ?. Required "> name required </p> <p * ngIf =" mobile. errors ?. ValidateMobile "> incorrect Phone Number Format </p> </div>

The above is the Angular2 form User-Defined validators introduced by xiaobian. I hope this will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.