开发者

Regex to validate a number with only one digit following a decimal

I have a regex which validates the user in entering a number with only one digit after a decimal.

However, if I enter: 0.1, 0.2, 0.3, ..., 0.9, it says invalid 开发者_开发问答for each. How do I correct this regex to also accept the above values?

/^[1-9][0-9]{0,3}$|^[1-9][0-9]{0,3}[\.][0-9]$/


You're requiring the first digit to be 1-9.


I think what you want is even simpler than what you have there. Your regex is failing because of the [1-9] at the start since it is forcing the answer to have a 1-9 at the beginning so...

/^[0-9][0-9]{0,3}$|^[1-9][0-9]{0,3}[\.][0-9]$/

I might be mistaken but I think you could do all of this with a much more simplified regex...

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


/^[0-9]{0,4}$|^[0-9]{0,4}[\.][0-9]$/

Or more succinctly

/^\d{0,4}$|^\d{0,4}[\.]\d$/

You were requiring [1-9] prior to the decimal.


Since your regex is structured to disallow leading zeros in the existing cases, you probably want to permit only one zero before the decimal point when the integer portion is zero. That means adding another alternative:

/^(?:[1-9][0-9]{0,3}$|[1-9][0-9]{0,3}\.[0-9]|0\.[0-9])$/

But what about 0 alone? Is it valid input? If so, you can make the fraction part optional in that alternative:

/^(?:[1-9][0-9]{0,3}$|[1-9][0-9]{0,3}\.[0-9]|0(?:\.[0-9])?)$/

That also allows 0.0. If you don't want that, you can change the final [0-9] to [1-9]:

/^(?:[1-9][0-9]{0,3}$|[1-9][0-9]{0,3}\.[0-9]|0(?:\.[1-9])?)$/

Also, notice how I enclosed the alternation in a group, so I only have to use one ^ and one $ for the whole regex.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜