1

i'm currently using this regex

"/^([0-9\(\)\/\+ \-]*)$/",

which is fine,but the problem is i am also using a masking script, which produces this line automatically,

(___) ___-____

and it messes up my validation, what regex code can allow me to verify only this type of input from the use

(999) 999-9999

and also not accept a "blank" input field from user when entered. any length is fine, as long as it only accepts this inputs that i mentioned above.

1
  • You should provide more specificity in your regex. Instead of putting a * on a giant set of characters (which matches 0 or more of the provided characters), you should aim to break it up into smaller subsets and specify specific amounts of characters for each. Oct 14, 2012 at 17:53

3 Answers 3

2

This should work:

^\(\d{3}\)\s{0,1}\d{3}-\d{3}$

Breaking this regexp:

\(\d{3}\) matches only three numbers between brackets.

\s{0,1} matches only 0 or 1 space.

\d{3}-\d{3} matches only three numbers followed by '-' and then three other numbers.

0

First, when asking about regular expressions, you should always say which language or tool you are using because that affects what features are available and which characters need to be quoted with backslash. I'll assume you're asking about JavaScript based on your question's tags.

You say any length is fine. I shall take that to mean that each sequence of consecutive digits can contain any number of digits from one to infinity. I shall assume there's exactly one space and exactly one dash. On that basis, your RE is:

/^\(\d+\) \d+-\d+$/

If, as is more likely, you want to limit the lengths of the digit sequences, you would say something like:

/^\(\d{3,4}\) \d{3}-\d{1,10}$/

(three or four digits, exactly three digits, one to ten digits).

I have omitted any capturing parentheses (...) , which are a bit redundant if you're capturing the whole string ^(....)$ .

Here's a concise summary of JavaScript regex syntax: http://www.regextester.com/jssyntax.html

0

Formatting and validation are two very different things. If you try to mix them, you will fail.

That being said, before performing validation you should strip all formatting characters from your string, then validate the content.

// remove everything that isn't a digit
var strippedNumber = value.replace(/\D/g, '');

if (strippedNumber.length === 10) {
    // valid phone number
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.