Implementation of ANGULAR2 form customization Validator _angularjs

Source: Internet
Author: User
Tags export class git clone

This article mainly introduces how to judge the results of the validator. Here, let's look at how to implement a custom validator.

Goal

We want to implement a verification of the phone number of the validator, the use of the example or based on the previous article inside the example, that is, the user information entered the form page. We add a validator that verifies the phone number on the element of the cell phone number. Then, if the phone number verification fails, an error is displayed, as follows:

The code for this section of the tutorial can be obtained from GitHub:

git clone

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

If you want to run, go to the project directory, run the following command to install dependencies and then run the test server:

CD angular2-forms-tutorial
git checkout model-driven # Check out the tag npm used in this article
install
NPM start

Implementing validators

In Angular2, the implementation of a validator is very simple, is a method can be, the parameter of the method is a formcontrol, the result is an error object or null. This is the case with the Typescript interface:

Interface Validator<t extends formcontrol> {
(c:t): {[Error:string]:any};
}

If you are familiar with object-oriented languages such as Java, the above interface definition is easy to understand. Where <t extends formcontrol> refers to the use of a generic T in this method, which is an object that inherits from FormControl. (c:t): {[Error:string]:any}; This is the method definition of a lambda expression, the type of parameter C is T, and this method returns an object.

We create a file called Mobile.validator.ts, which reads as follows:

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 validation method, the type of parameter C is FormControl, which is the form control, and he has a value property that holds the current values. We use regular expressions to determine whether the value is legitimate. If it is illegal, it returns an object.
In the previous tutorial, we obtained the verification results for the validator:

<p *ngif= "UserForm.controls.mobile?" Errors? Required > must enter the phone </p>

UserForm.controls.mobile is the form of the mobile phone number of this control, required is the required validator corresponding key, when the required validator failure, it will add a value in the errors:

{
required: {Valid:false}}
}

So, we implement the custom validator, also want to validate the results with the name of the validator as key, put in the errors, that is:

{
validatemobile: {valid:false}}
}

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

Add validators to a model-driven form

Next, we add the validator we implemented to our form and add it to the model-driven table dropdowns:

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 (one), Validators.maxlength (11), Validatemobile]]
});
...
}

The above code omits the other parts, complete code, please refer to GitHub.

In the code above, we introduced the custom validator that was previously implemented, and then added a validatemobile to the mobile control in the form control creation code.

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

<p *ngif= "UserForm.controls.mobile.errors?" Validatemobile "> Phone number format is incorrect </p>

This completes the validator and displays the validation results on the page, as simple as this.

Add validators to a template-driven form

However, if our form is not created in a model-driven fashion in an assembly, but instead created with HTML elements on the page, then using a custom validator is a bit more cumbersome.

In a template-driven form, we use validators like this:

<input type= "text" name= "mobile" [(Ngmodel)]= "user.mobile" #mobile = "Ngmodel" Required minlength= "one" maxlength= "11 ">
<span *ngif=" Mobile.valid "> Effective </span>
<div [hidden]=" mobile.valid | | mobile.pristine " >
<p *ngif= "Mobile.errors?" minlength | | Mobile.errors? MaxLength "> Telephone length must be 11</p>
<p *ngif=" Mobile.errors? Required "> must enter name </p>
</div>

This is to add a validator to the properties of the input entry element. So, we have to implement our own validator to use in the form, in addition to the validator method above, there are 2 things to do:

We need to define this validator as an instruction directive so that angular will identify our custom validator instructions when parsing the HTML.
We also need a angular validator to invoke our authentication method.
So, in the previous Mobile.validator.ts file, add the following directive definition:

@Directive ({
selector: ' [Validatemobile][ngmodel] '
})
export class Mobilevalidator {}

This code is very simple, that is, using the @directive tag to define an instruction Mobilevalidator, which acts as an element of both Validatemobile and Ngmodel attributes. In this way, we can add an attribute to the element on the cell phone to make the validator Directive work.
Then we also need the angular validator framework to call our validation methods, which requires ng_validators. Our instructions for modifying the validator above are defined as follows:

@Directive ({
selector: ' [Validatemobile][ngmodel] ',
providers: [
{provide:ng_validators, Usevalue: Validatemobile, multi:true}
]
})
export class Mobilevalidator {}

This allows the angular validator to apply the Validatemobile method to this instruction.

Finally, we add this new instruction to Appmodule's declarations, and we can use this validator on the page.

Finally, the code for using the validator on the page is as follows:

<input type= "text" name= "mobile" [(Ngmodel)]= "user.mobile" #mobile = "Ngmodel" Required minlength= "one" maxlength= "11 "Validatemobile>
<span *ngif= mobile.valid" > Effective </span>
<div [hidden]=] mobile.valid | | Mobile.pristine ">
<p *ngif=" Mobile.errors? minlength | | Mobile.errors? MaxLength "> Telephone length must be 11</p>
<p *ngif=" Mobile.errors? Required "> must enter name </p>
<p *ngif=" Mobile.errors? Validatemobile "> Phone number format is not correct </p>
</div>

The above is a small set to introduce the Angular2 form of the custom validator, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.