Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a Number field in Javascript using Regular Expressions?

Tags:

javascript

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.

like image 213
Vaibhav Jhaveri Avatar asked Mar 29 '13 07:03

Vaibhav Jhaveri


People also ask

How do you validate a number in JavaScript?

Approach: We have used isNaN() function for validation of the textfield for numeric value only. Text-field data is passed in the function and if passed data is number then isNan() returns true and if data is not number or combination of both number and alphabets then it returns false.

How do you check if a number is regular expression?

Validating Numeric Ranges. If you're using the regular expression to validate input, you'll probably want to check that the entire input consists of a valid number. To do this, replace the word boundaries with anchors to match the start and end of the string: ^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$.

How do you validate expressions in regex?

To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything. So there's no need to write your own RegExp validator.

How do you evaluate a regular expression in JavaScript?

JavaScript | RegExp test() Method The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false. Where str is the string to be searched.


2 Answers

You can test it as:

/^\d*$/.test(value)

Where:

  1. The / at both ends mark the start and end of the regex
  2. The ^ and $ at the ends is to check the full string than for partial matches
  3. \d* looks for multiple occurrences of number charcters

You do not need to check for both \d as well as [0-9] as they both do the same - i.e. match numbers.

like image 153
techfoobar Avatar answered Oct 10 '22 14:10

techfoobar


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
like image 31
Sergey Sahakyan Avatar answered Oct 10 '22 13:10

Sergey Sahakyan