Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Price field validation using javascript either jquery?

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

like image 974
Aaru Avatar asked Oct 16 '25 14:10

Aaru


1 Answers

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.

like image 96
David H. Bennett Avatar answered Oct 18 '25 08:10

David H. Bennett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!