David David - 1 month ago 29
TypeScript Question

Min / Max Validator in Angular 2 Final

According to thoughtgram.io, the currently supported validators are:


  • required

  • minlength

  • maxlength

  • pattern



So, considering the following code (plunkr here):

@Component({
selector: 'my-app',
template: `

<form #formRef="ngForm">
<input type="number" [(ngModel)]="firstValue" name="firstValue" min="0" required/>
<input type="text" [(ngModel)]="secondValue" maxlength="5" name="secondValue" required/>
<button type="submit"> Submit </button>
</form>

FORM: {{formRef.form | json }}
`
})
export class AppComponent {
firstValue = -22;
secondValue = "eyy macarena!";
}


While
minlength
is supported,
min="0"
is ignored by angular validation:

enter image description here

enter image description here

So, to make the form result in an error when firstValue ngModel < 0, do I need to build a custom validator?

Answer

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
  • minlength
  • maxlength
  • pattern
  • nullValidator

Validator: Here is my toned version of number Validator, you can improve it as you like

static number(prms = {}): ValidatorFn {
    return (control: FormControl): {[key: string]: string} => {
      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 number
var 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 value
var 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}))
Comments