[Angular2 Form] Model driven Form Custom Validator

Source: Internet
Author: User

In this tutorial we were going to learn what simple it was to create custom form field driven validators while using Angular 2 model driven forms. These type of validators is really just plain functions that follow a set of conventions.

We is going to learn how to write a custom form validator and what the validating function needs to return with order to re SPECT the Angular 2 form field validation contract.

Define a custom validator:

Import {FormControl} from "@angular/forms"; export function validateduration (Ctrl:formcontrol) {ConstNumValue =parseint (Ctrl.value); ConstValid = NumValue <Ten; returnValid?NULL: {validateduration: {valid:false, message:"Duration should less than"    }  }}

It just a function which return null or object, is it have error, it should return an object.

this. Reactiveform = fb.group ({      ...      Duration: [        0,        [          validators.required,          //  Validators.pattern (' [0-9]+ '),          validateduration        ]      ],      ...    });

We add ' validateduration ' to our validators array.

Use it:

  <Divclass= "Form-field">    <label>Duration:</label>    <inputFormcontrolname= "duration">    <Div*ngif= "ReactiveForm.controls.duration.errors?". Validateduration ">{{reactiveForm.controls.duration.errors?. Validateduration.message}}</Div>  </Div>

[Angular2 Form] Model driven Form Custom Validator

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.