简体   繁体   中英

Regex for float(x,y) possible?

In the following, float(x,y) means a number with x total digits and y of them can be decimals.

I am trying to do client side validation for an html input field. The field corresponds to a MySQL column with data type float(x,y). I know I can define a pattern for float(5,2) with lots of 'ors'. Is there an efficient way of generating a regex for this such that I can encode it in my web document?

Something of a workaround is to specify "\\d+(.\\d{1,y})?" and then set 'maxlength=x+1'. It is 'x+1' because the decimal place is counted. This then will allow the submission of an integer of length 'x+1' contrary to specification. I realize I can do Javascript validation but I want to do it with HTML validation.

You can first check the total length with a lookahead and then check for the length of numbers after the decimal point.

If you want X total number of digits and at most Y decimal points, you can use:

^(?=.{X+1}$)([1-9]\d*|0)\.\d{1,Y}$

Explanation:

^         asserts you are in the start position of the line
(?=       lookahead (zero length) match for:
    .{X + 1}     X+1 characters
    $            end of line //now you have asserted the total length
the whole part either
    0            is a single zero
    [1-9]\d*     more than a single digit and does not start with zero     
\.        a dot for the decimal point
\d{1,Y}   at least 1 and at most Y digits
$         asserts end of line

Note that you do not need to check the length of the whole part since you are already checking for the total length and the length of digits after the decimal so the part before the decimal point is automatically correct.

Example:

For X = 5 and Y = 2 , you will have:

^(?=.{8}$)([1-9]\d*|0)\.\d{1,2}$

Regex101 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