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

Scarnet
  • 490
  • 2
  • 6
  • 19

1 Answers1

19

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;
}
Community
  • 1
  • 1
Sergio
  • 28,539
  • 11
  • 85
  • 132