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
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
Share Improve this question asked Feb 1, 2014 at 6:04 AaruAaru 8134 gold badges13 silver badges29 bronze badges 2- stackoverflow./questions/15958808/… – Zero Fiber Commented Feb 1, 2014 at 6:07
- No need for Regex if you are using HTML5: jsfiddle/DerekL/6djkS – Derek 朕會功夫 Commented Feb 1, 2014 at 6:12
3 Answers
Reset to default 7First 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 remend you consider using that plug-in as it contains a lot of other features.
In HTML5 it supports checking validity natively if the browser supports it:
$("#foo").blur(function(){
alert(this.checkValidity());
});
Demo: http://jsfiddle/DerekL/6djkS/
You can always fall back to the good old ugly Regex if the browser does not support it.
Basing on the Number definition used in JSON:
(source: json)
(with the negative, scientific notation parts removed.)
var regex = /^\d*(.\d{2})?$/;
regex.test(price); //Boolean
For https://stackoverflow./a/21494842/1885344, the correct regex would be
var regex = /^\d*(\.\d{2})?$/;
regex.test(price); //Boolean
As it is now, it would permits all character as the decimal separator where as it should be only dot (.) character.