As I understand it (perhaps not well as I only started looking at this today) there is are validators built in to Angular that will check the max and min value of an <input type='number'>.
I tried to get this working in the app I'm building but it only comes up invalid when the input is completely empty. Other values validate, even numbers outside of my min/max range.
I tried to replicate it in a plunk but here it is just always valid. I'm at the end of a long day - can anyone just explain what I have to do to make the field in my plunk be valid with values of 5-10 and invalid when outside this range, empty or otherwise just...invalid.
As the documentation linked in your question states :
max()exists only as a function, not as a directive
That's due to the two issues cited in @DeborahK comments.
But still if you really want to use template-driven forms you can put those directives back in place :
import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, Validators, AbstractControl } from '@angular/forms';
@Directive({
selector: 'input[max]',
providers: [{provide: NG_VALIDATORS, useExisting: MaxValidator, multi: true}]
})
export class MaxValidator implements Validator {
@Input() max:number;
validate(control: AbstractControl): {[key: string]: any} {
if(typeof this.max == 'string') this.max = +this.max;
return this.max ? Validators.max(this.max)(control) : null;
}
}
I'll let you refactor it to get the MinValidatorone!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With