Reputation: 45
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)
Upvotes: 1
Views: 5032
Reputation: 45
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})?$
Upvotes: 1
Reputation: 22114
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.
Upvotes: 0
Reputation: 18354
function validate(str){
var fvalue = parseFloat(str);
return !isNaN(fvalue) && fvalue != 0;
}
Upvotes: 4