user6534060 user6534060 - 4 months ago 30
Javascript Question

JQuery : validate price float (7,2)

i'm using jquery validation plugin.

i have to validate price input.

the column in my database is float(7,2)
so my price accept


  • maximum 7 numbers without comma
    or

  • 5 number before comma and 2 after comma (as max)



I already did the validation in server side with this php code

if (strstr($price, '.') && (strlen(substr(strrchr($price, "."), 1)) > 2 || strlen($price) > 8 ) ) {
echo "invalid format";
}
elseif (!strstr($price, '.')) {
if(strlen($price) > 5 )
{
echo "invalid format";
}
}


i need to make the same validation in client side with adding new method using jquery validation plugin.

but i can't find the true reg expression to do that.


Update



detail description :

i need to accept any number less than or equal 7 digits like (12 - 1234 - 1234567 ) .. - .. and any number with less than or equal 5 digits before comma and less than or equal 2 digits after comma like (123.1 - 12345.12 - 12.23 )

Answer

Update

detail description : i need to accept any number less than or equal 7 digits like (12 - 1234 - 1234567 ) .. - .. and any number with less than or equal 5 digits before comma and less than or equal 2 digits before comma like (123.1 - 12345.12 - 12.23 )

Should "and less than or equal 2 digits before comma" be "and less than or equal 2 digits after comma"?


Edit, Updated

You can use pattern attribute with RegExp \d{1,5},\d{1,2}|\d{1,7}

<form>
  <input type="text" 
         pattern="\d{1,5},\d{1,2}|\d{1,7}" 
         title="a) any number less than or equal 7 digits; b) any number with less than or equal 5 digits before comma and less than or equal 2 digits after comma" 
         required />
  <input type="submit" />
</form>