I have a price field in my form i should allow decimal or floating point numbers only , not characters and any other special and white spaces in my price field.
How could i get that?
This is my code :
$("#foo").blur(function() {
var price = $("#foo").value;
var validatePrice = function(price) {
return /^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$/.test(price);
}
alert(validatePrice(price)); // False
});
Fiddle
First off, here's the corrected code:
$("#foo").blur(function() {
var price = $("#foo").val();
var validatePrice = function(price) {
return /^(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(price);
}
alert(validatePrice(price)); // False
});
You will need to test for empty values (undefined) separately. Also, if you want to allow negative values use:
/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(price);
This regular expression was lifted from the JQuery Validate plug-in by Jörn Zaefferer. I recommend you consider using that plug-in as it contains a lot of other features.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With