Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom validation input type number angular 2

I would like to know how to set a min and max number in angular2 when we try to limit an input text it's very simple we have to put any ideas about limiting the number for exemple 3 numbers

it work perfect on type text but with number I think we have to do a directive

like image 445
imtah Avatar asked Jun 24 '26 17:06

imtah


1 Answers

Angular provide some Validators like required,maxLength.. but you can create your own Validator like this :

  1. Create a fonction (this one take your control value, check if it's between 0 and 100. If it's okay, it returns null, which means no problems, otherwise you return an object with valid to false)
function validateNumber(c: FormControl) {
  return c.value > 0 && c.value < 100 ? null : {valid: false}
};
  1. Put your function as a Validator in your control : new FormControl('', validateNumber)
like image 101
patchimou Avatar answered Jun 26 '26 16:06

patchimou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!