`ng-pattern` - how to check for only numbers?

user2024080 picture user2024080 · Dec 23, 2015 · Viewed 75.2k times · Source

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

Answer

RIYAJ KHAN picture RIYAJ KHAN · Dec 23, 2015

Use this expression

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

UPDATE :

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

ng-pattern="/^[a-zA-Z]*$/"