I'm tring to validate a number text box in angular. Only digits, a single ma, or a single dot is accepted. Alphabets and multiple dots or mans are invalid.
My regex is this:
/\d{1,}[,.]{0,1}\d{0,}/
There are some matching and non matching values here: if needed.
Valid values:
1111
1.1111
111.111
111,11
1,1
1
Invalid values:
1d11e
1..1
1.,1
1,,1
111.11.1
1,111.11
But for whatever reason, angular textbox seems think everything is invalid, except an empty text box. I'm quite confused why:
<input type="text" ng-model="idNumber" ng-pattern="customPattern" />
// in .js
$scope.customPattern = '\d{1,}[,.]{0,1}\d{0,}';
Is there anything else I need to add?
Thanks.
ps: I'm on angular 1.5x
I'm tring to validate a number text box in angular. Only digits, a single ma, or a single dot is accepted. Alphabets and multiple dots or mans are invalid.
My regex is this:
/\d{1,}[,.]{0,1}\d{0,}/
There are some matching and non matching values here: https://regexr./3k4hl if needed.
Valid values:
1111
1.1111
111.111
111,11
1,1
1
Invalid values:
1d11e
1..1
1.,1
1,,1
111.11.1
1,111.11
But for whatever reason, angular textbox seems think everything is invalid, except an empty text box. I'm quite confused why:
<input type="text" ng-model="idNumber" ng-pattern="customPattern" />
// in .js
$scope.customPattern = '\d{1,}[,.]{0,1}\d{0,}';
Is there anything else I need to add?
Thanks.
ps: I'm on angular 1.5x
Share Improve this question asked Feb 1, 2018 at 17:43 LocustHordeLocustHorde 6,42916 gold badges66 silver badges99 bronze badges 4-
1
Use
^\d+(?:[,.]\d+)?$
(withm
flag for online IDEs) – ctwheels Commented Feb 1, 2018 at 17:44 - @ctwheels was about to post exactly the same solution but you beat me to it :) – Gurmanjot Singh Commented Feb 1, 2018 at 17:46
- @ctwheels... that works! I spent like 20 minutes wondering if ng-pattern had some obscure spec -_- Can you please make that an answer so I can accept when SO allows me? thanks. – LocustHorde Commented Feb 1, 2018 at 17:47
-
1
First of all,
'\d{1,}[,.]{0,1}\d{0,}'
is a string (not aRegExp
literal), so\d
should be\\d
. – kamoroso94 Commented Feb 1, 2018 at 17:54
1 Answer
Reset to default 6See regex in use here
^\d+(?:[,.]\d+)?$
^
Assert position at the start of the line\d+
Match one or more digits(?:[,.]\d+)?
Optionally match the following[,.]
Match a character in the set (either,
or.
)\d+
Match one or more digits
$
Assert position at the end of the line
Notes:
{1,}
is the same as+
{0,1}
is the same as?
{0,}
is the same as*