Apparently, this code is trying to validate a phone number by matching any alpha characters in the phone number -- if a match is made, then the phone number is invalid.
So you want any alpha character (optionally embedded inside non-whitespace characters, though these are listed as optional, so they're actually irrelevant) except for the sequence x
(space x space) to match and trigger failure.
This sounds like you want accept the case of people embedding an extension into the phone number, as in: 123-123-1234 x 789
.*([a-zA-Z])+(?<! x).*
comes very close.
EDIT: This uses a negative look-behind construction. (?<!
allows the regex to keep going only if from the current match position, the previous characters do not match what's inside the remainder of the parentheses. So, if there was a leading x
it would fail the match.
--
Using this regex, the following don't match:
- 123-123-1234
- 123-123-1234 x789
- 123-123-1234 x 789
But it does match:
- 123-123a-1234
- 123-123 asdfasdf 12312
- 123-123x-123123
- 123-123 xfasdf
And the ones that match are invalid, by virtue of the !
in your if-statement.
But having said that, your code would be much easier if you wrote the phone number validation as a positive validation (i.e. what do you allow), not a negative invalidation (what do you specifically avoid). By writing what you allow, you'll be able to prevent edge cases much easier.
For example, the following is not matched by both regex's:
- 123-###-1234
- 123-!$#&^(##^#*@#(!@&#(#-1234
and this would return true from your function. Is that what you really want?
I strongly suggest positive validation, not negative invalidation.
EDIT: @Aprillion suggests this previous linked question: A comprehensive regex for phone number validation
This shows how complicated phone number validation can be (especially if you're validating for more than 1 country). There's a lot of good suggestions in there, though it's not be the be-all-end-all summary. My inclination would be on the front-end to allow only digits (w/ an optional free-from comment field) for phone number entry.
I must admit also, that, it does give me a little less confidence on positive validation -- especially if you have to deal w/ an arbitrary international #.
A lot would be dependent upon the OP's real requirements.