18

I am using an ng-pattern to check for ONLY numbers in my input. But for me that's not working. I can able to type in characters after the number. How can I restrict that?

here is my code :

<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
    <input type="text" ng-model="price" name="price_field" ng-pattern="/^[0-9]/" required>
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <input type="submit" value="submit"/>
</form>
</div>

Live Demo

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
user2024080
  • 1
  • 14
  • 56
  • 96

4 Answers4

38

Use this expression

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

UPDATE :

for accepting the only characters,you can use like this.

ng-pattern="/^[a-zA-Z]*$/"
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
7

Try this regex: It should work /^[0-9]+$/ + sign is for accepting one or more digits.

Vishal Rajole
  • 1,504
  • 1
  • 13
  • 19
5

ng-pattern="/^[0-9]*$/" //change to

ng-pattern="/^\d{1,10}$/"

NOTE: '\d' can check not only 0-9, also for many digits like greek digits

AlokeT
  • 1,086
  • 7
  • 21
Ahmed MR-mody
  • 61
  • 1
  • 6
1

For reactive form

this.form = fb.group({

  number: ['', [Validators.required, Validators.pattern("^[0-9]*$")]]

})
San Jaisy
  • 15,327
  • 34
  • 171
  • 290