`ng-pattern` - how to check for only numbers?
Asked Answered
C

4

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

Charterhouse answered 23/12, 2015 at 6:21 Comment(2)
For accepting only number in your text box i think better you can use type="number" in your input tag.Unhinge
u may refer to this thread: #19828070Unseam
B
38

Use this expression

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

UPDATE :

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

ng-pattern="/^[a-zA-Z]*$/"
Broaden answered 23/12, 2015 at 6:30 Comment(4)
Ok. for accepting charactors can i use ng-pattern="/^[a-z][A-Z]*$/"- ?Charterhouse
What is the exact requirement?Broaden
only need to allow characters ( name field )Charterhouse
it didn't work for angularjs 1.2.x, it also allows charactersWellspring
F
7

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

Fahland answered 23/12, 2015 at 6:31 Comment(0)
S
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

Screwball answered 23/12, 2015 at 6:39 Comment(1)
why do want to change it? what is the benefit in this approach?Charterhouse
P
1

For reactive form

this.form = fb.group({

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

})
Phosphorescence answered 11/6, 2021 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.