简体   繁体   中英

ng-pattern that allows decimal ratios

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..

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM