angularjsangularjs-forms

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


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


Solution

  • Use this expression

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

    UPDATE :

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

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