Reputation: 437
var cost_price = "15..00"
/*Cost price should be such that it should contain numbers and may not contain more than one dot*/
if(/^([0-9])|([.])/.test(cost_price)){
documet.write("Correct cost price");
}
Now despite of two dots in the cost_price I get the hello message. What should I change in the if condition?
P.S. I have combined 2 reg ex. one checks for correctness of digits and others checks to see if the dot occurs only once.
Upvotes: 0
Views: 40
Reputation: 98921
var cost_price = "15..00"
if (/\d+\.\d+/.test(cost_price)) {
documet.write("Correct cost price");
} else {
documet.write("Incorrect cost price");
}
http://regex101.com/r/cL8pP1
EXPLANATION:
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “.” literally «\.»
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Upvotes: 0
Reputation: 39542
Why not go for
/^[0-9]+(\.[0-9]+)?$/
and hence make the last part completely optional? (the ?
specifies "matched 0 to 1 times")
In case you want to allow .15
, you can change the first [0-9]+
(matched 1 to infinity times) to [0-9]*
(matched 0 to infinity times).
Upvotes: 4