问题
I'm having an ng-pattern
that validates for a ration like 4:6 as shown below:
ng-pattern="/^(\d+):(\d+)$/"
I want also to validate if decimal numbers are entered as rations along with the above validation.Example :5.4:7.1
I trid by giving ng-pattern
as
ng-pattern="/^(\.[0-9]{1,2}+):(\.[0-9]{1,2}+)$/"
But not triggering the validation.Please suggest me where I'm going wrong..
回答1:
Your ^(\.[0-9]{1,2}+):(\.[0-9]{1,2}+)$
is not a valid pattern in JS as the limiting quantifier {min,max}
cannot be followed with +
(no possessive quantifiers are supported by JS regex engine). Even if you remove the pluses and use ^(\.[0-9]{1,2}):(\.[0-9]{1,2})$
, the pattern would match strings like .1:.3
or .34:.45
and would not allow 3:45
(dots would be obligatory).
Use the following regex if you want to allow values like .5
:
ng-pattern="/^\d*\.?\d+:\d*\.?\d+$/"
See the regex demo.
Alternatively, you may use
ng-pattern="/^(\d+\.)?\d+:(\d+\.)?\d+$/"
to only allow numbers with non-empty integer part. See this regex demo.
来源:https://stackoverflow.com/questions/41395451/ng-pattern-that-allows-decimal-ratios