I am trying to implement input number field which will allow positive or negative numbers.
I have used "/^0|[1-9]\d*$/"
regex expression for ng-pattern.
But it is not working.For character input it is not showing any error.
I have pasted my code here.
I don't want to make this field as required.I just want only number validation(charters are not allowed).
There are a couple of problems with your code:
The pattern /^0|...$/
is interpreted as /(^0)|(...$)/
. So, your pattern will accept any string that either begins with 0
(no matter what follows) or ends with any digit in [1-9] (optionally followed by any number of digits).
The correct pattern is: /^(0|[1-9][0-9]*)$/
(note that \d
will match more characters than [0-9], e.g. arabic digit symbols etc).
The input elements of type number are handled in the following way by the browser:
If their content is not a valid number, then their value
property is set to ''
.
Thus, entering 1w3
will cause the value
to be an empty string, so then pattern will not be applied.
You should use an input element of type text
.
(This is not directly related to your question, but I noticed in your fiddle, you were using <form>.<input>.$invalid
, instead of the (probably) intended <form>.<input>.$valid
.
$invalid
is a property of the FormController
only.)
Based on the above, your code should look more like this:
<input type="text" name="price_field" ng-model="price"
ng-pattern="/^(0|[1-9][0-9]*)$/" />
(For accepting negative numbers as well, change ng-pattern
to /^(0|\-?[1-9][0-9]*)$/
.)
See, also, this short demo.
(UPDATE: The demo has been updated to illustrate the differences between number- and text-fields and between different patterns.)
used htm5 pattern for input number only
<input type="number" name="country_code" pattern="[0-9]" >
Why do not use required
with min
. So we can write:
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="number"
ng-model="price"
ng-init="price=0"
name="price_field"
min="0"
required
>
<span ng-show="myForm.price_field.$error.required ||
myForm.price_field.$error.min">Not a valid number!</span>
<input type="submit" value="submit" />
</form>
</div>
Demo Fiddle
Howevewr if you still want to use pattern, remove type="number"
. I'm not sure but sounds like type number
has own pattern, this is a reason why it doesn't work.
Here is 2nd Demo Fiddle