ASP.NET Regex to validate mobile phone number - javascript

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.

Related

Validating client-side data input using a pattern

I am currently working on a project whereby data can be added into a database via a website. Currently I have managed to configure it so that the form accepts title, postcode, vehicle reg and ID number.
Javascript validation is working fine for these entries, with the exception of ID number. All ID numbers are a specific format (2 numbers followed by a . followed by 4 numbers).
I cannot seem to work out how to define the pattern.
Due to the size of my code, I have not posted the full code here (all is validating except this ID validation), but I've provided a snip of the 'if' statement below which I'm trying to come up with.
if (inputElement.id == "wid") {
pattern = /^[a-zA-Z0-9 ]*$/;
feedback = "Only 2 numbers followed by a . followed by 4 numbers are
permitted";
I know that the pattern isn't correct here but I have searched for hours trying to locate some easy to explain guidance and cannot find anything which appears to be relevant.
Any thoughts would be appreciated.
Thank you
You can try out something like https://regex101.com/ to test you regexes, and see an explanation of it.
I think your pattern should be this: /^[0-9]{2}\.[0-9]{4}$/.
The first part ([0-9]{2}) makes sure that the id starts with 2 digits, then a dot \. (which must be escaped, because it means "every character" otherwise) and then 4 digits [0-9]{4}

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.

Javascript regex to validate a phone number

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

JavaScript regex valid name

I want to make a JavaScript regular expression that checks for valid names.
minimum 2 chars (space can't count)
space en some special chars allowed (éàëä...)
I know how to write some seperatly but not combined.
If I use /^([A-Za-z éàë]{2,40})$/, the user could input 2 spaces as a name
If I use /^([A-Za-z]{2,40}[ éàë]{0,40})$/, the user must use 2 letters first and after using space or special char, can't use letters again.
Searched around a bit, but hard to formulate search string for my problem. Any ideas?
Please, please pretty please, don't do this. You will only end up upsetting people by telling them their name is not valid. Several examples of surnames that would be rejected by your scheme: O'Neill, Sørensen, Юдович, 李. Trying to cover all these cases and more is doomed to failure.
Just do something like this:
strip leading and trailing blanks
collapse consecutive blanks into one space
check if the result is not empty
In JavaScript, that would look like:
name = name.replace(/^\s+/, "").replace(/\s+$/, "").replace(/\s+/, " ");
if (name == "") {
// show error
} else {
// valid: maybe put trimmed name back into form
}
Most solutions don't consider the many different names there might be. There can be names with only two character like Al or Bo or someone that writes his name like F. Middlename Lastname.
This RegExp will validate most names but you can optimize it to whatever you want:
/^[a-z\u00C0-\u02AB'´`]+\.?\s([a-z\u00C0-\u02AB'´`]+\.?\s?)+$/i
This will allow:
Li Huang Wu
Cevahir Özgür
Yiğit Aydın
Finlay Þunor Boivin
Josué Mikko Norris
Tatiana Zlata Zdravkov
Ariadna Eliisabet O'Taidhg
sergej lisette rijnders
BRIANA NORMINA HAUPT
BihOtZ AmON PavLOv
Eoghan Murdo Stanek
Filimena J. Van Der Veen
D. Blair Wallace
But will not allow:
Shirley24
66Bryant Hunt88
http://stackoverflow.com
laoise_ibtihaj
hippolyte#example.com
Cy4n 4ur0r4 Blyth3 3ll1
Justisne
Danny
If the name needs to be capitalized, uppercase, lowercase, trimmed or single spaced, that's a task a formatter should do, not the user.
I would like to propose a RegEx that would match all latin based languages with their special characters:
/\A([ áàíóúéëöüñÄĞİŞȘØøğışÐÝÞðýþA-Za-z-']*)\z/
P.S. I've included all characters I could find, but please feel free to edit the answer in case I've missed any.
Why not
var reg= /^([A-Za-z]{2}[ éàëA-Za-z]*)$/;
2 letters, then as many spaces, letters or special characters as you want.
I wouldn't allow spaces in usernames though - it's begging for trouble when you have usernames like
ab ba
who's going to remember how many spaces they used?
You could do this:
/^([A-Za-zéàë]{2,40} ?)+$/
2-40 characters, and then optionally a space, repeated at least once. This will allow a space at the end, but you could trim it off separately.
After 'trim' the input value, The following will math your request only for Latin surnames.
rn = new RegExp("([\w\u00C0-\u02AB']+ ?)+","gi");
m = ln.match(rn);
valid = (m && m.length)? true: false;
Note that I am using '+', instead of '{2,}', that is because some surnames uses just one letter in a separated word like "Ortega y Gasset"
You can see I am not using RegExp.test, this is because that method don't work properly (I don't know why, but it has a high fail-rate, you may see it here:.
In my country, people from non-latin-language countries usually do some translation of their names so the previous RegExp would be enough. However, if you attempt to match any surname in the world, you may add more range of \u#### characters, avoiding to include symbols, numbers or other type. Or perhaps the xregexp library may help you.
And, please, do not forget to test the input in server side, and escaping it before using it in the sql sentences (if you have them)

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