Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching exactly 10 digits in Javascript [duplicate]

Tags:

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

like image 530
Force444 Avatar asked Aug 13 '14 12:08

Force444


People also ask

How do you match numbers in JavaScript?

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 .

What is RegExp in JavaScript?

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 .

Which RegEx matches one or more digits?

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.

What is $1 and $2 in JavaScript?

A piece of JavaScript code is as follows: num = "11222333"; re = /(\d+)(\d{3})/; re. test(num); num. replace(re, "$1,$2");


2 Answers

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.

like image 86
Braj Avatar answered Jan 20 '23 16:01

Braj


You can use this:

var pattern = /^[0-9]{10}$/; 
like image 20
Nikhil Khullar Avatar answered Jan 20 '23 18:01

Nikhil Khullar