Javascript regex to validate a phone number - javascript

I am working to modify a script. The script contains a form to allow visitors to send an SMS to phone numbers. In the form I have a text box in which users enter the phone number of the text receiver. I am using a regex to validate the phone number to prevent spammers and make sure the user typed the correct number.
Here are the default phone numbers used in Afghanistan:
+93785657024
+93795657024
+93700565656
+93775657024
The regex validation first should make sure that +93 is used, then make sure that 78, 77, 79 or 700 (one of these) is used after +93 and finally followed by 6 digits.
Here is the Javascript code I am trying to fix. This code now works only for +937 followed by 8 digits.
<script type="text/javascript">
function test (){
var phoneRegex = new RegExp('^937\d{8}$');
var phoneNum = document.getElementById("receiver").value;
if(!(phoneRegex.test(phoneNum))) {
alert("Invalid Phone Number");
document.getElementById("receiver").focus();
} else {
alert("valid");
}
}
</script>

The regex validation first should make sure that +93 is used, then make sure that 78, 77, 79 or 700 (one of these) is used after +93 and finally followed by 6 digits.
This answer will not work except in the 700 case because the OP specified that all prefixes were followed by 6 digits, when in fact only 93700 is followed by 6, and the other prefixes are followed by 7 digits.
/^\+93(77\d|78\d|79\d|700)\d{6}$/
should do it.
Your original regex doesn't require a "+" at the front though.

I think this would suit your condition
Totally you need 11 digits prefixed with +.
Therefore if 77|78|79 means followed by 7 digits or if 700, followed
by 6 digits.
var reg = /^\+93((77|78|79)\d{7}|700\d{6})$/;
console.log(reg.test('+93705657024'));
Check this Fiddle

Regular expression itself:
var phoneRegex = new RegExp('(937(?:00\\d{6}|[789]\\d{7}))');
Notes:
Since you are using new RegExp, I have not inserted / and / around the expression. (I am mentioning this because you commented that some of the other answers did not work at all, and I suspect that is because you may have forgotten to remove the / and / before testing them, perhaps? There seem to be minor problems with them which is why I am also answering, but the other answers should at least match some valid phone numbers if you remove the / and / that surround the regular expressions.)
You seem to have made a mistake in counting the digits vs. the examples you gave of valid Afghanistan phone numbers. +9377, +9378, etc. are followed by 7 digits rather than 6, while only +93700 is actually followed by 6.
My expression puts the full phone number into the temporary variable $1, which can come in handy. (I used a non-capturing group for the alternatives in the second part of the match because extra captures sometimes can be a bother when I want to do something else with the results of the match. For what your code is doing, it would work the same with or without the ?: that my regular expression contains.)
My expression does not anchor the match to the beginning or end of the string, because doing so would return false for valid numbers that had punctuation, like the + that you showed in your own phone numbers.
For the same reason, I suggest that you delete non-numeric characters before checking input for a valid phone number. Right now phone numbers using parentheses or hyphens or any traditional punctuation will return false even though they are actually valid.
This modification of your code would work for ensuring that valid phone numbers are recognized correctly by first removing punctuation:
if(!(phoneRegex.test(phoneNum.replace(/\D+/g, '')))) {
If you make this modification to your code, then it would be appropriate to add the anchoring expressions ^ and $ around my suggested regular expression to make sure it only contained a valid phone number, not a longer number such as a credit card number.
There is a problem with the way your code checks the results from doing the regular expression test. This code will work better for you:
<script type="text/javascript">
function test (){
var phoneField = document.getElementById("receiver")
var phoneNum = phoneField.value;
if (/^(937(?:00\d{6}|[789]\d{7}))$/.test(phoneNum.replace(/\D+/g, ''))) {
alert('valid');
} else {
alert('Invalid phone number');
phoneField.focus();
}
}
</script>
<input id="receiver" value="+93785657024" />
<input type="button" onclick="test()" value="Check this number" />
Note: I got some of my code mixed up. Please ignore my other code (the one that was uploaded to that link, I mean). This one works.

Use:
/^\+937([789]|00)\d\d\d\d\d\d$/
That should do it.
+937 All your numbers start with this
([789]|00) Either 7, 8, 9 or 00
\d\d\d\d\d 6 digits

Related

Javascript regex failing but not sure why

I'm trying to validate UK postcodes using javascript and as far as I can tell from reading on threads on stack, the following should work fine. However no matter what valid UK postcode I've tried so far, the if statement fails. I'm a bit of a newb to javascript,
var postcode = $("#postcode").val().toUpperCase();
var regex = new RegExp("^((GIR &0AA)|((([A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]))) &[0-9][ABD-HJLNP-UW-Z]{2}))$");
if(regex.test(postcode)){
alert('yes');
} else {
alert('no');
}
As mentioned in comments, your problem seems to be the ampersands &. Somewhat simplified and corrected I believe your regex should be:
^(GIR 0AA|(?:[A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?|[A-PR-UWYZ][0-9][A-HJKSTUW]|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]) [0-9][ABD-HJLNP-UW-Z]{2})$
Capturing the whole value, from begining of line to end, it matches
Girobank's PC
or
one of the other combinations (separated by | inside a non-capturing group (?:...)) followed by the terminating space, digit, letter, letter.
Hope this helps.
Regards

Email Validation RegEx username/local name length check not running

I've debugged for a few hours now and have hit a wall - regex has never been my strongsuit. I have been able to alter the following regex to restrict 255 characters for domain fine, however, in trying to restrict the local/username portion of an email address I'm running into issues implementing a 64 character limit. I've gone through regex101 replacing +s and *s and attempting to understand what each pass is doing - however, even when I add a check against all non-whitespace characters with a limit of 64 it seems like the other checks pass and take precedence - although I'm not sure. Below is my regex currently without any of the 64 character checks that I've broken it with:
var emailCheck = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.{0,1}([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]){1,255}([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]){1,255}([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.*$/i);
What I have so far can be seen at http://jsfiddle.net/mtqx0tz1/ , I've made other slight alterations (e.g. not allowing consecutive dots) but for the most part this regex comes from another stack post without the character limits.
Lastly, I'm aware this isn't the 'standard' so to speak and emails are checked server-side, however, I would like to be more safe than sorry...as well as work on some of my regex. Sorry if this question isn't worthy of an actual post - I'm just simply not seeing where in my passes {1,64} is failing. At this point I'm thinking about just sub-stringing the portion of the string up to the # sign and checking length that way...but it would be nice to include it in this statement since all the checks are done here to begin with.
I have used this regex validation and it works good.
The e-mail address is in the variable strIn
try
{
return Regex.IsMatch(strIn,
#"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}
catch (RegexMatchTimeoutException)
{
return false;
}

Phone number validation - excluding non repeating separators

I have the following regex for phone number validation
function validatePhonenumber(phoneNum) {
var regex = /^[1-9]{3}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
return regex.test(phoneNum);
}
However, I would liek to make sure it doesn;t pass for different separators such as in
111-222.3333
Any ideas how to make sure the separators are the same always?
Just make sure beforehand that there is at most one kind of separator, then pass the string through the regex as you were doing.
function validatePhonenumber(phoneNum) {
var separators = extractSeparators(phoneNum);
if(separators.length > 1) return false;
var regex = /^[1-9]{3}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{3}$/;
return regex.test(phoneNum);
}
function extractSeparators(str){
// Return an array with all the distinct chars
// that are present in the passed string
// and are not numeric (0-9)
}
You can use the following regex instead:
\d{3}([-\s\.])?\d{3}\1?\d{4}
Here is a working example:
http://regex101.com/r/nN9nT7/1
As result it will match the following result:
111-222-3333 --> ok
111.222.3333 --> ok
111 222 3333 --> ok
111-222.3333
111.222-3333
111-222 3333
111 222-3333
EDIT: after Alan Moore's suggestion:
Also matches 111-2223333. That's because you made the \1 optional,
which isn't necessary. One of JavaScript's stranger quirks is that a
backreference to a group that did not participate in the match,
succeeds anyway. So if there's no first separator, ([-\s.])? succeeds
because the ? made it optional, and \1 succeeds because it's
JavaScript. But I would have used ([-\s.]?) to capture the first
separator (which might be nothing), and \1 to match the same thing
again. This works in any flavor, including JavaScript.
We can improve the regex to:
^\d{3}([-\s\.]?)\d{3}\1\d{4}$
You'll need at least two passes to keep this maintainable and extensible.
JS' RegEx doesn't allow for creating variables for use later in the RegEx, if you want to support older browsers.
If you are only supporting modern browsers, Fede's answer is just fine...
As such, with ghetto-support, you aren't going to be able to reliably check that one separator is the same value every time, without writing a really, really, really, stupidly-long RegEx, using | to basically write out the RegEx 3 times.
A better way might be to grab all of the separators, and use a reduction or a filter to check that they all have the same value.
var userEnteredNumber = "999.231 3055";
var validNumber = numRegEx.test(userEnteredNumber);
var separators = userEnteredNumber.replace(/\d+/g, "").split("");
var firstSeparator = separators[0];
var uniformSeparators = separators.every(function (separator) { return separator === firstSeparator; });
if (!uniformSeparators) { /* also not valid */ }
You could make that a little neater, using closures and some applied functions, but that's the idea.
Alternatively, here's the big, ugly RegEx that would allow you to test exactly what the user entered.
var separatorTest = /^([0-9]{3}\.[0-9]{3}\.[0-9]{3,4})|([0-9]{3}-[0-9]{3}-[0-9]{3,4})|([0-9]{3} [0-9]{3} [0-9]{3,4})|([0-9]{9,10})$/;
Notice I had to include the exact same number-test three times, wrap each one in parens (to be treated as a single group), and then separate each group with an | to check each group, like an if, else if, else... ...and then plug in a separate special case for having no separator at all...
...not pretty.
I'm also not using \d, just because it's easy to forget that - and . are both accepted "digit"s, when trying to maintain one of these abominations.
Now, a word or two of warning:
People are liable to enter all kinds of crap; if this is for a commercial site, it's likely better to just strip separators entirely and validate the number is the right size, and conforms to some specifics (eg: doesn't start with /^555555/).
If not given any instruction about number format, people will happily use either no separator or a formal number, like (555) 555-5555 (or +1 (555) 555-5555 for the really pedantic), which is obviously going to fail hard, in this system (see point #1).
Be prepared to trim what you get, before validating.
Depending on your country/region/etc laws about data-security and consumer-vs-transaction record-keeping (again, may or may not be more important in a commercial setting), it's likely better to store both a "user-given" ugly number, and a system-usable number, which you either clean on the back-end, or submit along with the user-entered text.
From a user-interaction perspective, either forcing the number to conform, explicitly (placeholders showing them xxx-xxx-xxxx right above the input, in bold), or accepting any text, and prepping it yourself, is going to be 1000x better than accepting certain forms, but not bothering to tell the user up-front, and instead telling them what they did was wrong, after they try.
It's not cool for relationships; it's equally not cool, here.
You've got 9-digit and 10-digit numbers, so if you're trying for an international solution, be prepared to deal with all international separators (, \.\-\(\)\+) etc... again, why stripping is more useful, because THAT RegEx would be insane.

ASP.NET Regex to validate mobile phone number

I have an application to send TAN to users via SMS. We have already API to send SMS to a mobile phone number. Therefore, I have to make sure it's correct mobile phone number. Below is my regex:
function validateMobile(str) {
var filter = /^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$/;
if (!filter.test(str)) {
alert('Please provide a valid mobile phone number');
return false;
}
return true;
}
It doesn't accept characters, only number and '+' allowed. Users can enter, for example +49176xxxxxxxx or 0176xxxxxxxx (no particular country code)
But this regex is seriously flawed. Users can enter whatever numbers, e.g. 1324567982548, this regex also returns true. I thought about to check the length of the textbox, it'd work, for the time being, but still it's not a proper solution.
Is there any other better regex or way to check more concrete a mobilbe phone number?
Thanks in advance.
SOLVED
I solved this with a new regex:
var filter = /^(\+49\d{8,18}|0\d{9,18})((,\+49\d{8,18})|(,0\d{9,18}))*$/;
or as mzmm56 suggested below:
var filter = /^(?:(\+|00)(49)?)?0?1\d{2,3}\d{8}$/;
Both are equally fine.
i think that you may need to restrict the regex to mobile number format of the country you're targetting, if possible, or check the input against a variety of patterns according to different countries' mobile number formats. it also seems like your regex would match .- instead of " only number and '+' ".
anyway—in Germany, i believe the following regex would work, only allowing a single + at the beginning, and then nothing but numbers:
^(?:(\+|00)(49)?)?0?1\d{2,3}\d{8}$
with 0?1\d{2,3} it's taking into account that German mobile numbers may or may not start with 0, begin with 1, and are followed by another 2 numbers (in your case 76), or 3 numbers (176) if there was no leading 0.
It might be easier to to strip off all non-numeric characters (except + perhaps), then regex it, then if you need to output it, just reformat it.
Here's a regex for the phone number after non-numeric characters have been stripped:
^\+[1-9]{1}[0-9]{10}$
For more detailed info on country codes, see this post.

How to modify regex for phone numbers and accept only digits

I have this following regex method for the jquery validate plugin.
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
Currently, its validating against phone numbers in this format : 203-123-1234
I need to change to validate like this: 2031231234
Does anyone have a quick and easy solution for me?
You can replace
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
with this
phone_number.match(/\d{10}/);
\d means match any digit
and
{10} means 10 times
Getting rid of all those -? sequences is probably the quickest way - they mean zero or one - characters.
That will reduce it to:
/^(1)?(\([2-9]\d{2}\)|[2-9]\d{2})[2-9]\d{2}\d{4}$/
whih can be further simplified to:
/^1?(\([2-9]\d{2}\)|[2-9]\d{2})[2-9]\d{6}$/
If you also want to disallow the brackets around area codes, you can further simplify it to:
/^1?[2-9]\d{2}[2-9]\d{6}$/
(and, technically, it won't match the literal 203-123-1234 since the character immediately after that first - has to be 2 thru 9, so I'm assuming you were just talking about the format rather than the values there).
I think better approach would be changing the whole expression with simpler version, something like this:
/^[0-9]{10}$/
Edited, Note (see comments):
This is just a limited example of how to validate a format: 111-222-3333 vs 1112223333, not proper US phone number validation.
If you just want ten digits, then
phone_number.match(/\d{10}/)
will do it. If you want to match any of the other conditions in there (eg match both 1-2031231234 and 2031231234), you will need to add more.
As a side note, what you currently have doesn't match 203-123-1234 because the first digit after the first hyphen is a 1, and it is looking for 2-9 in that spot.
([0-9]{10}) this will match with 10 digit number.
You can use if you want to match all formats, including 203-123-1234 and 2031231234
EDIT : I'm no regex expert, but I added "1-" support
/^(?:1-?)?[(]?\d{3}[)]?\s?-?\s?\d{3}\s?-?\s?\d{4}$/
By the way, there's a really nice AIR tool for regex, it's called RegExr and you can get the desktop version here http://www.gskinner.com/RegExr/desktop/ or use the online version http://gskinner.com/RegExr/ . There's also a "community" section that contains a lot of useful working regex. That's where I took that one.

Categories

Resources