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
You could use /^\d+$/
.
That means:
^
string start\d+
a digit, once or more times$
string endThis 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/
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With