Question

I am working with EXT-JS and am using a VType to specify the regex for a particular field in a form.

I need this field to accept values like: 1, 11, 11561.464, 1.0, 56.0, etc and reject values like:

.1, 1., 56.(I need my values to start and end with a digit)

I have used the following regular expressions:

  1. /^([0-9][0-9]*)([.])?([0-9]*[0-9])$/
    This accepts values like 21.,.1 2.2 and rejects values like 1., 2.,1.0

  2. /^\d+(\.\d)?/
    This accepts values like 1.,11.

  3. /^\d+\.?(\d+)$/
    This accepts values like 11., 1.1,11.1 and rejects values like 1.

Why is it the same regular regex rejects values like 1.(Single digit + a decimal, which is acceptable) but accepts values like 11.(double digit + a decimal, which is totally unacceptable)

Was it helpful?

Solution

Your second pattern is pretty much all the way there. One thing: you forgot the string-end anchor:

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

Now there can be no trailing periods.

Another thing: you should repeat the second \d+ as well, unless you want to limit yourself to one decimal place:

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

Finally, it's generally good practice to suppress capturing unless you explicitly need it:

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

OTHER TIPS

You can try this for both

/^\d+(\.\d+)?$/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top