I've tried other questions on SO but they don't seem to provide a solution to my problem:
I have the following simplified Validate function
function Validate() { var pattern = new RegExp("([^\d])\d{10}([^\d])"); if (pattern.test(document.getElementById('PersonIdentifier').value)) { return true; } else { return false; } }
I've tested to see if the value is retrieved properly which it is. But it doesn't match exactly 10 digits. I don't want any more or less. only accept 10 digits otherwise return false.
I can't get it to work. Have tried to tweak the pattern in several ways, but can't get it right. Maybe the problem is elsewhere?
I've had success with the following in C#:
Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)")
Examples of what is acceptable:
0123456789 ,1478589654 ,1425366989
Not acceptable:
a123456789 ,123456789a ,a12345678a
To match all numbers and letters in JavaScript, we use \w which is equivalent to RegEx \[A-za-z0–9_]\ . To skip all numbers and letters we use \W . To match only digits we use \d . To not match digits we use \D .
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .
Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.
A piece of JavaScript code is as follows: num = "11222333"; re = /(\d+)(\d{3})/; re. test(num); num. replace(re, "$1,$2");
You can try with test()
function that returns true/false
var str='0123456789'; console.log(/^\d{10}$/.test(str));
OR with String#match()
function that returns null
if not matched
var str='0123456789'; console.log(str.match(/^\d{10}$/));
Note: Just use ^
and $
to match whole string.
You can use this:
var pattern = /^[0-9]{10}$/;
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