简体   繁体   中英

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

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.

In HTML5 it supports checking validity natively if the browser supports it:

$("#foo").blur(function(){
    alert(this.checkValidity());
});

Demo: http://jsfiddle.net/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.org )

(with the negative, scientific notation parts removed.)

var regex = /^\d*(.\d{2})?$/;
regex.test(price);   //Boolean

For https://stackoverflow.com/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM