Min / Max Validator in Angular 2 Final
To apply min/max validation
on a number
you will need to create a Custom Validator
Validators class currently only have a few validators, namely
- required
- requiredTrue
- minlength
- maxlength
- pattern
- nullValidator
- compose
- composeAsync
Validator: Here is toned down version of my number Validator, you can improve it as you like
static number(prms = {}): ValidatorFn { return (control: FormControl): {[key: string]: any} => { if(isPresent(Validators.required(control))) { return null; } let val: number = control.value; if(isNaN(val) || /\D/.test(val.toString())) { return {"number": true}; } else if(!isNaN(prms.min) && !isNaN(prms.max)) { return val < prms.min || val > prms.max ? {"number": true} : null; } else if(!isNaN(prms.min)) { return val < prms.min ? {"number": true} : null; } else if(!isNaN(prms.max)) { return val > prms.max ? {"number": true} : null; } else { return null; } }; }
Usage:
// check for valid numbervar numberControl = new FormControl("", [Validators.required, CustomValidators.number()])// check for valid number and min value var numberControl = new FormControl("", CustomValidators.number({min: 0}))// check for valid number and max valuevar numberControl = new FormControl("", CustomValidators.number({max: 20}))// check for valid number and value range ie: [0-20]var numberControl = new FormControl("", CustomValidators.number({min: 0, max: 20}))
I found a library implementing a lot of custom validators - ng2-validation - that can be used with template-driven forms (attribute directives). Example:
<input type="number" [(ngModel)]="someNumber" name="someNumber" #field="ngModel" [range]="[10, 20]"/><p *ngIf="someNumber.errors?.range">Must be in range</p>
You can implement your own validation (template driven) easily, by creating a directive that implements the Validator
interface.
import { Directive, Input, forwardRef } from '@angular/core'import { NG_VALIDATORS, Validator, AbstractControl, Validators } from '@angular/forms'@Directive({ selector: '[min]', providers: [{ provide: NG_VALIDATORS, useExisting: MinDirective, multi: true }]})export class MinDirective implements Validator { @Input() min: number; validate(control: AbstractControl): { [key: string]: any } { return Validators.min(this.min)(control) // or you can write your own validation e.g. // return control.value < this.min ? { min:{ invalid: true, actual: control.value }} : null }}