'How to validate a Number field in Javascript using Regular Expressions?
Is the following correct?
var z1=^[0-9]*\d$;
{
if(!z1.test(enrol))
{
alert('Please provide a valid Enrollment Number');
return false;
}
}
Its not currently working on my system.
Solution 1:[1]
var numberRegex = /^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)([Ee][+-]?\d+)?\s*$/
var isNumber = function(s) {
return numberRegex.test(s);
};
"0" => true
"3." => true
".1" => true
" 0.1 " => true
" -90e3 " => true
"2e10" => true
" 6e-1" => true
"53.5e93" => true
"abc" => false
"1 a" => false
" 1e" => false
"e3" => false
" 99e2.5 " => false
" --6 " => false
"-+3" => false
"95a54e53" => false
Solution 2:[2]
Try:
var z1 = /^[0-9]*$/;
if (!z1.test(enrol)) { }
Remember, * is "0 or more", so it will allow for a blank value, too. If you want to require a number, change the * to + which means "1 or more"
Solution 3:[3]
You this one and it allows one dot and number can have "positive" and "negative" symbols
/^[+-]?(?=.)(?:\d+,)*\d*(?:\.\d+)?$/.test(value)
Solution 4:[4]
If you looking for something simple to test if a string is numeric, just valid numbers no +, - or dots.
This works:
/^\d*$/.test("2412341")
true
/^\d*$/.test("2412341")
false
Solution 5:[5]
you can also use this regular expression for number validation
/^\/(\d+)$/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | Jean |
| Solution 5 | Ashwani Kumar Kushwaha |
