Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  158] [ 7]  / answers: 1 / hits: 18914  / 8 Years ago, sun, april 3, 2016, 12:00:00

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


More From » regex

 Answers
16

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;
}

[#62718] Thursday, March 31, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
helenat

Total Points: 450
Total Questions: 95
Total Answers: 97

Location: Central African Republic
Member since Mon, Aug 10, 2020
4 Years ago
;