View Full Version : Checking textbox for correct format

04-21-2012, 02:58 AM
I have a standard textbox with a default value of 0.00 the customer needs to enter a value that is in the same format.

I am guessing preg_match would be the right code to use? I need to allow up to 7 digits and only two ending digits. So basically 0.01 to 9999999.99
But need to block if it's like 50000 or 500,00 etc. I could make two different textboxes, but I want them to be the same field in the database if possible.


<b>Price:</b></td><td><input type="text" name="price" size="6" maxlength="9" value="0.00">

04-21-2012, 03:31 AM
I think the REGEX you'll want is this: ^[0-9]{1,7}[.][0-9]{2}$

This will allow 1 to 7 digits up front, a decimal point, and then two digits after the decimal.


if( !preg_match( '/^[0-9]{1,7}[.][0-9]{2}$/', $myPriceField ) )
echo( "Whoops! Someone didn't follow the format." );

I would, however, for user clarity purposes, add some JavaScript to the client side to help the user format better (i.e: as they're typing, do some auto format if possible).