问题
I need a javascript/jQuery routine that validates a string to allow only negative, positive or decimal numbers(ex. -1 or -41.02 or 20 or 2.20 or 10.05)
回答1:
function validate(str){
var fvalue = parseFloat(str);
return !isNaN(fvalue) && fvalue != 0;
}
回答2:
The regular expression given below solves the issue, it works for -ve decimal numbers.
^-?[0-9]{0,4}(.^-[0-9]{1,4})?$|^(100)(.^-[0]{1,4})?$
回答3:
One way to do this is to parse the value and see if you get a valid number.
You can also use regular expression for even more complex data type matching.
Try the following:
[-+]?([0-9]*\.[0-9]+|[0-9]+)
Also look here for further information.
来源:https://stackoverflow.com/questions/5880186/jquery-allow-only-negative-positive-or-decimal-number-validation