10

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.

1
  • 1
    Close, a RegExp literal is enclosed in forward slashes: /^[0-9]*\d$/. You could also use /^\d+$/. Note that if the test passes, it just means its all digits, it isn't necessarily a valid enrolment number. Commented Mar 29, 2013 at 9:07

6 Answers 6

25

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Does not handle floats
/^\d*$/.test(''); it fails for empty string
17
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

1 Comment

This works great. Thanks. Was tearing my hair out trying to find a just such a solution. Can also use just ^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)?\s*$ if you don't require the scientific notation support.
3

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"

Comments

3

You this one and it allows one dot and number can have "positive" and "negative" symbols

/^[+-]?(?=.)(?:\d+,)*\d*(?:\.\d+)?$/.test(value)

Comments

0

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

Comments

0

you can also use this regular expression for number validation

/^\\/(\d+)$/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.