Reputation: 1565
i am looking for a regular expression to put in ng-pattern attribute of angular.
i am looking for an expression that satisfies only a specific decimal pattern i.e.
exactly one digit --> than a decimal --> exactly 2 digits
i came up with
\d{1}\.{1}\d{2}?
The above pattern matches the following numbers correctly.
2.22
3.12
0.34
which is fine but if user enters 12.12
it doesn't reject this as I need it to.
Upvotes: 1
Views: 581
Reputation: 6486
If you want precisely this content and nothing else, you should use the start of word (^
) and end of word ($
) anchors. Your regex would be:
var regex = /^\d\.\d{2}$/; //then just bind to controller
According to the ng-pattern
documentation
If the expression evaluates to a RegExp object, then this is used directly. If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in
^
and$
characters. For instance,"abc"
will be converted tonew RegExp('^abc$')
.
Note that if you use a string input, you'll have to escape the backslashes to get the proper regex string. In this case you could just use
<input ng-model="yourModel" ng-pattern="\\d\\.\\d{2}" >
Upvotes: 1
Reputation: 784868
exactly one digit --> than a decimal --> exactly 2 digits
Use word boundaries to prevent it to match unwanted text on either side:
\b\d\.\d{2}\b
Upvotes: 1