24

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

Force444
  • 3,321
  • 9
  • 39
  • 77
  • 3
    Bob's your uncle `^[0-9]{10}$`. `^` means begin of string and `$` means end of string. – HamZa Aug 13 '14 at 12:32
  • Thanks. It seems to work. Can you recommend a good link/text/tutorial on regular expressions? I seem to have just jumped into it and it gets quite messy sometimes. – Force444 Aug 13 '14 at 12:35
  • 1
    BTW, quoted characters passed to the RegExp constructor must be double quoted: `new RegExp('^\\d{10}$')` should do the trick. A literal is simpler: `/^\d{10}$/`. – RobG Aug 13 '14 at 12:36
  • 1
    http://www.regular-expressions.info/ as well as [Stack Overflow: What does this regex mean?](http://stackoverflow.com/questions/22937618) – Evan Davis Aug 13 '14 at 12:37

3 Answers3

43

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.

Braj
  • 46,415
  • 5
  • 60
  • 76
14

You can use this:

var pattern = /^[0-9]{10}$/;
Nikhil Khullar
  • 703
  • 6
  • 21
10

You can try this :

var str = "0123456789";
var pattern = new RegExp("^[0-9]{10}$");
pattern.test(str);
Karsan
  • 269
  • 3
  • 14