7

I was very surprised that I didn't find this already on the internet. is there's a regular expression that validates only digits in a string including those starting with 0 and not white spaces

here's the example I'm using

  function ValidateNumber() {

  var regExp = new RegExp("/^\d+$/");
  var strNumber = "010099914934";
  var isValid = regExp.test(strNumber);
  return isValid;
}

but still the isValid value is set to false

5
  • 1
    Can you show a example of the content you want to test? Just /^\d+$/ should work... Commented Apr 3, 2016 at 8:26
  • 1
    share what you tried so far? Commented Apr 3, 2016 at 8:27
  • 2
    ^\d+$..I am also surprised that you didn't make an attempt to write this regex Commented Apr 3, 2016 at 8:27
  • 1
    @Scarnet, added a detail to my answer that you missed. The string should be double escaped like this "^\\d+$" Commented Apr 3, 2016 at 9:07
  • 1
    It is on the Internet. It's in any page describing regular expressions. Commented Apr 3, 2016 at 9:24

1 Answer 1

21

You could use /^\d+$/.

That means:

  • ^ string start
  • \d+ a digit, once or more times
  • $ string end

This way you force the match to only numbers from start to end of that string.

Example here: https://regex101.com/r/jP4sN1/1
jsFiddle here: https://jsfiddle.net/gvqzknwk/


Note:

If you are using the RegExp constructor you need to double escape the \ in the \d selector, so your string passed to the RegExp constructor must be "^\\d+$".


So your function could be:

function ValidateNumber(strNumber) {
    var regExp = new RegExp("^\\d+$");
    var isValid = regExp.test(strNumber); // or just: /^\d+$/.test(strNumber);
    return isValid;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.