-2

How can I validateonly type number with javascript? for example. I want only this pattern to check in my phone number field "(033) 123-45-67"

Abhijit Muke
  • 1,194
  • 3
  • 16
  • 41
  • 5
    There are countless examples of this available all over the internet (including here), please search before posting. http://stackoverflow.com/search?q=javascript+phone+number – Cᴏʀʏ Jan 08 '14 at 13:59

3 Answers3

4

Use Regular Expression

var regexp = /^\(\d{3}\)\s\d{3}-\d{2}-\d{2}$/;

regexp.test('(033) 123-45-67'); // true
regexp.test('(0331) 123-45-67'); // false
regexp.test('(033 123-45-67'); // false
regexp.test('(033) 123+45-67'); // false
siniy
  • 271
  • 1
  • 2
2

You use a regular expression.

/^\(\d{3}\) \d{3}-\d{2}-\d{2}$/

^ indicates the start of the string, $ indicates the end of the string, \d is shorthand for 0-9, {n} means the preceeding must match exactly n times, and since parenthesis are special characters you need to escape them as \( and \).

Eric
  • 6,965
  • 26
  • 32
1

You could use "regular expressions" to match patterns in strings, such as phone numbers. For example, the folowing pattern,

\(\d\d\d\) \d\d\d-\d\d-\d\d

would match the phone number you gave. Each part of the expression is meant to match some part of the given string. In this case, for example, \d matches a "digit", and \( matches an opening parenthesis. There are also plenty of short-cuts and tricks you can do to make cooler more flexible patterns. Read up on regular expressions on the internet.

P.S. while you are out there learning about regex, you might find regexpal.com useful for testing your sweet patterns!

Ziggy
  • 21,845
  • 28
  • 75
  • 104