Aashil
Aashil

Reputation: 437

Javascript reg ex combination

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

Answers (3)

Pedro Lobito
Pedro Lobito

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

h2ooooooo
h2ooooooo

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")

Regular expression visualization

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

anubhava
anubhava

Reputation: 785226

The regex should be this for your case:

/^\d+(\.\d+)?$/

Upvotes: 1

Related Questions