0

Am using the regex /^[0-9]+$/ to limit the input of the text box to only accept numbers. It's working fine but when the types something like +124 then also it's not setting the text box as invalid.

<form name="myForm" novalidate>
  <input type="number" ng-model="age" name="age" ng-pattern="/^[0-9]+$/" />
  <h3>Valid Status : {{myForm.age.$valid}}</h3>
</form>

Input: 123 Output: myForm.age.$valid - true

Input: -123 Output: myForm.age.$valid - false

Input: +123 Output: myForm.age.$valid - true (shouldn't be true)

https://plnkr.co/edit/3OVE6qiWgJozUb3hyFQ5?p=preview

vinnu313
  • 1
  • 1
  • @WiktorStribiżew Why can't it work with type="number" ?? With type="text" browsers let the users type arbitrary characters too. – vinnu313 Jul 28 '16 at 10:58
  • 1
    Well, regular expressions work with *string* input, regex engines do not allow any other *type* as input. So, only `password`, `text` are usually valid types that will work with a regex. – Wiktor Stribiżew Jul 28 '16 at 11:09

2 Answers2

0

If you want to make the pattern work, you need to set the type attribute to text. Since you also want to let users type only digits into the input field, add an onkeypress validation:

<input type="text"  onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" ng-model="age" name="age" ng-pattern="/^[0-9]+$/" />

Actually, you won't even need the ng-pattern regex then.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
-1

You can just use:

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

Without setting the input type to number (as default it is text and it should work fine).

Here JSFiddle: https://jsfiddle.net/3ju3b2tu/1/