Reputation: 6409
I'm tring to validate a number text box in angular. Only digits, a single comma, or a single dot is accepted. Alphabets and multiple dots or commans are invalid.
My regex is this:
/\d{1,}[,.]{0,1}\d{0,}/
There are some matching and non matching values here: https://regexr.com/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
Upvotes: 2
Views: 4792
Reputation: 22837
^\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 lineNotes:
{1,}
is the same as +
{0,1}
is the same as ?
{0,}
is the same as *
Upvotes: 6