8

I want to validate a 9 digits number using angular,

this is in my modal :

<input type="number" class="form-control" ng-model="id" required>

i tried pattern = [0-9]{9}, seems its passing every number that its getting . I want to pass only number 000000000 - 9999999999 , min-max also not working for me.

this is what my app adding to this class:

 class="form-control ng-pristine ng-valid-number ng-invalid ng-invalid-required"

thank u !

2
  • you have min max attributes Nov 30, 2014 at 11:15
  • Cant use it, minimum value can be also 000000101 for example.
    – Elad Noty
    Nov 30, 2014 at 11:21

4 Answers 4

10

I just use a pattern as validator. The following code will make the field required and must be only digits of length 10

ngOnInit() {
    this.firstForm = this.fb.group({
        firstCtrl: ['', [Validators.pattern('^[0-9]{10}$'), Validators.required]],
    });
4

Have you tried both ngMinlength and ngMaxlength at the same time?

Example:

<input type="text" ng-minlength=9 ng-maxlength=9 />

Check out the official documentation regarding this: https://docs.angularjs.org/api/ng/directive/input

Very nice tutorial about form validation: http://www.ng-newsletter.com/posts/validations.html

3

As mentioned by Rahul Desai you have to use ngMinlength and ngMaxlength.
But since you want to use numbers you have to change the code a little bit to this

<input type="number" ng-model="id" ng-minlength=9 ng-maxlength=9 required />

To be honest I don't know what to do with class="form-control". Maybe you can add it or leave it out?!

Anyway you can also try this

<input type="number" ng-model="id" ng-pattern="/^[0-9]{1,9}$/" required />

You shouldn't need min/max attribute anymore.

EDIT:
I guess I made a mistake with the second one. It should be either

ng-pattern="/^[0-9]{9}$/"

or

ng-pattern="/^[0-9]{9,9}$/"
2
  • it didnt work for me. it accepts (3...5) or (2.5.44)
    – Alaa'
    May 16, 2019 at 13:50
  • @Alaa' what do you mean exactly? Did you try both or just one of the provided solutions? I guess I made a mistake in the second one. I didn't test it back then. The pattern one should work for sure. I don't know if angular allows dots in type 'number'. May 20, 2019 at 0:43
2

With Reactive Forms you should compose validators in such a way:

formControlYourField: [
  "",
  Validators.compose([
    Validators.required,
    Validators.minLength(9),
    Validators.maxLength(9),
    Validators.pattern("^[0-9]*$"),
  ]),
]

And of course in your .html

<input
  matInput
  required
  formControlName="formControlYourField"
  type="text"
  placeholder="123456789"
/>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.