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