Javascript Regex - What to use to validate a phone number? - javascript

Could anyone tell me what RegEx would work to validate an international phone number including white space between the numbers and also allowing for these chars: - ( ).
The amount of numbers in the string is not too important, I would just like the user to be able to type something like either example 1 or 2 if they wish:
Example:
+44 (0) 207 111 1111
442071111111
I have already read through and tested the posted answers to some similar questions to the best of my understanding but so far none of them are working for me the way I want them to.
Please can someone help me out with a clear explanation of how the above should be written for validation?
Many thanks to anyone who can help.

Try this code
HTML Code
<input type="text" id="phone"/>
JS Code
$("#phone").blur(function() {
var regexp = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/
var no = $("#phone").val();
if (!regexp.test(no) && no.length < 0) {
alert("Wrong phone no");
}
});

See A comprehensive regex for phone number validation
Quick cheat sheet
Start the expression: /^
If you want to require a space, use: [\s] or \s
If you want to require parenthesis, use: [(] and [)] . Using \( and \) is ugly and can make things confusing.
If you want anything to be optional, put a ? after it
If you want a hyphen, just type - or [-] . If you do not put it first or last in a series of other characters, though, you may need to escape it: \-
If you want to accept different choices in a slot, put brackets around the options: [-.\s] will require a hyphen, period, or space. A question mark after the last bracket will make all of those optional for that slot.
\d{3} : Requires a 3-digit number: 000-999. Shorthand for
[0-9][0-9][0-9].
[2-9] : Requires a digit 2-9 for that slot.
(\+|1\s)? : Accept a "plus" or a 1 and a space (pipe character, |, is "or"), and make it optional. The "plus" sign must be escaped.
If you want specific numbers to match a slot, enter them: [246] will require a 2, 4, or 6. [77|78] will require 77 or 78.
$/ : End the expression

This is a long regex, but it supports both formats (for example 2 to be a valid international number, is MUST start with either + or 00):
/^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i
This allows extensions and a multiple choice of formats and separators.
Matches:
(+351) 282 43 50 50
90191919908
555-8909
001 6867684
001 6867684x1
1 (234) 567-8901
1-234-567-8901 x1234
1-234-567-8901 ext1234
1-234 567.89/01 ext.1234
1(234)5678901x1234
(123)8575973
(0055)(123)8575973
On $n, it saves:
Country indicator
Phone number
Extention
This same answer was given here: A comprehensive regex for phone number validation (direct link to my answer)

/*
#isValidUSPhoneFormat function will check valid US Format
Allowed US Format
(123) 456-7890
123-456-7890
123.456.7890
1234567890
(734) 555.1212
*/
function isValidUSPhoneFormat(elementValue){
var phoneNumberPattern = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s.]{0,1}[0-9]{3}[-\s.]{0,1}[0-9]{4}$/;
if(phoneNumberPattern.test(elementValue) == false)
{
var phoneNumberPattern = /^(\()?\d{3}(\))?(.|\s)?\d{3}(.|\s)\d{4}$/;
return phoneNumberPattern.test(elementValue);
}
return phoneNumberPattern.test(elementValue);
}
May this will help you to understand JavaScript RegEx..

Don't even try. Trying to guard against what you think is invalid input can result in angry users who can't enter perfectly valid phone numbers. And if the user really wants to enter an invalid phone number, he/she will be able to do it anyway.

function checkPhoneNumber(val) {
var num = document.getElementById(val).value;
var mob=/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g;
if (mob.test(num) == false) {
alert("Please Enter Valid Phone Number.");
document.getElementById(val).value = "";
return false;
}
if (num.length > 15) {
alert("Only 15 characters allowed for Phone Number field.");
document.getElementById(val).value = "";
return false;
}
return true;
}
Try it Ones

Try using isValidPhoneNumber(phoneNumber, countryCode) method of libphonenumber-js package. First is the phone number with "+" at the start of it. The second argument is the country code (for eg: 'US', 'IN'). That helps you validate any international number accurately.

Best lib for international phone number: google/libphonenumber
Here is an example with CDN:
<script src="https://cdn.jsdelivr.net/npm/google-libphonenumber#3/dist/libphonenumber.min.js"></script>
// Format Phone Number
function formatPhone(p) {
var phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
var parsedPhone = phoneUtil.parse(p);
if (phoneUtil.isValidNumber(parsedPhone)) {
return phoneUtil.format(parsedPhone, libphonenumber.PhoneNumberFormat.INTERNATIONAL)
} else {
return NaN
}
}

A better option to validate international phone numbers in a loose way is as follows.This is not a strict validation
/^\s*(?:+?(\d{1,3}))?([-. (](\d{3})[-. )])?((\d{3})[-. ](\d{2,4})(?:[-.x ](\d+))?)\s*$/gm
A working Javascript function will look like this
function validatePhone(phone) {
var regex = /^\s*(?:\+?(\d{1,3}))?([-. (]*(\d{3})[-. )]*)?((\d{3})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$/gm;
return regex.test(phone);
}
console.log(validatePhone('+973 11111111')) // true
console.log(validatePhone('+973 XX77yyss')) // false
For those who wish to have more about the characters:
^ asserts position at the start of a line
\s matches any whitespace character (equivalent to [\r\n\t\f\v ])
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Non-capturing group (?:+?(\d{1,3}))?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
+ matches the character + with index 4310 (2B16 or 538) literally (case sensitive)
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy) 1st Capturing
Group (\d{1,3})
\d matches a digit (equivalent to [0-9])
{1,3} matches the previous token between 1 and 3 times, as many times as possible, giving back as needed (greedy) 2nd Capturing
Group ([-. (](\d{3})[-. )])?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy) Match a single
character present in the list below [-. (]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-. ( matches a single character in the list -. ( (case sensitive) 3rd Capturing Group (\d{3})
\d matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times Match a single character present in the list below [-. )]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-. ) matches a single character in the list -. ) (case sensitive) 4th Capturing Group ((\d{3})[-. ](\d{2,4})(?:[-.x
](\d+))?) 5th Capturing Group (\d{3})
\d matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times Match a single character present in the list below [-. ]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-. matches a single character in the list -. (case sensitive) 6th Capturing Group (\d{2,4})
\d matches a digit (equivalent to [0-9])
{2,4} matches the previous token between 2 and 4 times, as many times as possible, giving back as needed (greedy) Non-capturing
group (?:[-.x ]*(\d+))?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy) Match a single
character present in the list below [-.x ]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-.x matches a single character in the list -.x (case sensitive) 7th Capturing Group (\d+)
\d matches a digit (equivalent to [0-9])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
\s matches any whitespace character (equivalent to [\r\n\t\f\v ])
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line
This would test positive for the below patterns and more
+42 555.123.4567 +1-(800)-123-4567 +7 555 1234567 +7(926)1234567 (926) 1234567 +79261234567 926 1234567 9261234567 1234567 123-4567 123-89-01 495 123

Related

Javascript: Regex to exclude whitespace and special characters

I need a regex to validate,
Should be of length 18
First 5 characters should be either (xyz34|xyz12)
Remaining 13 characters should be alphanumeric only letters and numbers, no whitespace or special characters is allowed.
I have a pattern like here, '/^(xyz34|xyz12)((?=.*[a-zA-Z])(?=.*[0-9])){13}/g'
But this is allowing whitespace and special characters like ($,% and etc) which is violating the rule #3.
Any suggestion to exclude this whitespace and special characters and to strictly check that it must be letters and numbers?
You should not quantify lookarounds. They are non-consuming patterns, i.e. the consecutive positive lookaheads check the presence of their patterns but do not advance the regex index, they check the text at the same position. It makes no sense repeating them 13 times. ^(xyz34|xyz12)((?=.*[a-zA-Z])(?=.*[0-9])){13} is equal to ^(xyz34|xyz12)(?=.*[a-zA-Z])(?=.*[0-9]), and means the string can start with xyz34 or xyz12 and then should have at least 1 letter and at least 1 digits.
You may consider fixing the issue by using a consuming pattern like this:
If you do not care if the last 13 chars contain only digits or only letters, use the patterns suggested by other users, like /^(?:xyz34|xyz12)[a-zA-Z\d]{13}$/ or /^xyz(?:34|12)[a-zA-Z0-9]{13}$/
If there must be at least 1 digit and at least 1 letter among those 13 alphanumeric chars, use /^xyz(?:34|12)(?=[a-zA-Z]*\d)(?=\d*[a-zA-Z])[a-zA-Z\d]{13}$/.
See the regex demo #1 and the regex demo #2.
NOTE: these are regex literals, do not use them inside single- or double quotes!
Details
^ - start of string
xyz - a common prefix
(?:34|12) - a non-capturing group matching 34 or 12
(?=[a-zA-Z]*\d) - there must be at least 1 digit after any 0+ letters to the right of the current location
(?=\d*[a-zA-Z]) - there must be at least 1 letter after any 0+ digtis to the right of the current location
[a-zA-Z\d]{13} - 13 letters or digits
$ - end of string.
JS demo:
var strs = ['xyz34abcdefghijkl1','xyz341bcdefghijklm','xyz34abcdefghijklm','xyz341234567890123','xyz14a234567890123'];
var rx = /^xyz(?:34|12)(?=[a-zA-Z]*\d)(?=\d*[a-zA-Z])[a-zA-Z\d]{13}$/;
for (var s of strs) {
console.log(s, "=>", rx.test(s));
}
.* will match any string, for your requirment you can use this:
/^xyz(34|12)[a-zA-Z0-9]{13}$/g
regex fiddle
/^(xyz34|xyz12)[a-zA-Z0-9]{13}$/
This should work,
^ asserts position at the start of a line
1st Capturing Group (xyz34|xyz12)
1st Alternative xyz34 matches the characters xyz34 literally (case sensitive)
2nd Alternative xyz12 matches the characters xyz12 literally (case sensitive)
Match a single character present in the list below [a-zA-Z0-9]{13}
{13} Quantifier — Matches exactly 13 times

Regex allowing no leading whitespace but allowing anywhere else and requiring at least one uppercase and one lowercase letters

I want regex code to validate usernames that have:
length between 6 and 30
contain at least one letter from A-Z
contain at least one digit from 0-9
not contain a space at the beginning but it might have at
the end or in the middle.
may contain special characters
So far I have tried this:
^[\S](?=.*\d)(?=.*[A-Z]).{6,30}$
It works quite good but when I choose an uppercase letter ONLY at the beginning it doesnt validate my password.
Test12 34 ----> Doesnt accept but should accept
TesT12 34 ----> Accept
tesT12 34 ----> Accept
The problem arises because the \S is at the pattern start before the lookaheads. That means, that the lookaheads that require an uppercase ASCII letter and a digit only check them after the first character in string.
Now, there can be two scenarios: 1) there may be any amount of whitespace characters in the string, but at its beginning, 2) only one whitespace char is allowed in the string, and not in the beginning
Scenario 1
Put \S after the lookaheads and decrement the limiting quantifier values to set the limits to 6-30 as \S already matches and consumes the first char:
^(?=.*\d)(?=.*[A-Z])\S.{5,29}$
^^ ^^^^
See the regex demo.
JS test:
var rx = /^(?=.*\d)(?=.*[A-Z])\S.{5,29}$/;
var vals = [ "Test12 34", "TesT12 34", "tesT12 34" ];
for (var s of vals) {
console.log(s, "=>", rx.test(s));
}
Scenario 2
Use
^(?=.{6,30}$)(?=.*\d)(?=.*[A-Z])\S+(?:\s\S*)?$
The length is restricted with the positive lookahead at the beginning ((?=.{6,30}$)) and the consuming \S+(?:\s\S*)? pattern will only allow a single \s whitespace (1 or 0 due to the last ? - one or zero occurrences quantifier) and it can be in the middle (as the first \S is quantified with +, one or more occurrences quantifier) or end (as the \S after \s is *-quantified, zero or more occurrences quantifier).
See the regex demo.

Insert hyphen when regex group is not null or empty

I have a numeric code which varies in length from 6-11 digits
which is separated by hyphen after each 3 digits
possible combinations
123-456
123-456-78
123-456-7890
So, here I am trying to convert the user entered code to this format even when entered with spaces and hyphens in the middle.
For Ex:
123 456-7 -> 123-456-7
123456 789 -> 123-456-789
123456 -> 123-456
Valid user input format is 3digits[space or hyphen]3digits[space or hyphen]0to5digits
I tried it like this
code.replace(/^(\d{3})[- ]?(\d{3})[- ]?(\d{0,5})$/,'$1-$2-$3');
But when there are only 6 digits there is a hyphen(-) at the end of the number which is not desired.
123-456-
Could anybody help me with this? Thank you.
The easiest way is probably to just do this with a second replace:
code.replace(/^(\d{3})[- ]?(\d{3})[- ]?(\d{0,4})$/,'$1-$2-$3')
.replace(/-$/, '');
This is chaining a second replace function, which says "replace a - at the end of the string with an empty string". Or in other words, "if the last character of the string is - then delete it.
I find this approach more intuitive than trying to fit this logic all into a replace command, but this is also possible:
code.replace(
/^(\d{3})[- ]?(\d{3})[- ]?(\d{0,4})$/,
'$1-$2' + ($3 == null ? '' : '-') + $3
)
I think it's less obvious at a glance what this code i doing, but the net result is the same. If there was no $3 matched (i.e. your sting only contained 6 digits), then do not include the final - in the replacement.
I believe this will do it for you - replace
^(\d{3})[ -]?()|(\d{3})[ -]?(\d{1,5})
with
$1$3-$2$4
It has two alternations.
^(\d{3})[ -]?() matches start of line and then captures the first group of three digits ($1), then optionally followed by a space or an hyphen. Finally it captures an empty group ($2).
(\d{3})[ -]?(\d{1,5}) matches, and captures ($3), three digits, optionally followed by a space or an hyphen. Then it matches and captures (($4)) the remaining 1-5 digits if they're present.
Since the global flag is set it will make one or two iterations for each sequence of digits. The first will match the first alternation, capturing the first three digits into group 1. Group 2 will be empty.
For the second iteration the first match have matched the first three digits, so this time the second alternation will match and capture the next three digits into group 3 and then the remaining into group 4.
Note! If there only are three digits left after the first match, none of the alternations will match, leaving the last three digits as is.
So at the first iteration group 1 are digits 123. group 2, 3 and 4 are empty. The second iteration group 1 and two are empty, group 3 are the digits 456 and group 4 are digit 7-11.
This gives the first replace $1 = 123- plus nothing, and the second 456-67....
There's no syntax checking in this though. It assumes the digits has been entered as you stated they would.
See it here at regex101.

javascript - url regexp not proper

I am tryint to validate URL with js.
function validateURL(url) {
var urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.|https:\/\/|http:\/\/){1}([0-9A-Za-z]+\.)");
return urlregex.test(url);
}
but but i want that google.com will also pass, but it is not passing thru this regexp.
what is wrong with regexp?
I want these urls to pass thru regexp:
http://www.google.com
http://google.com
https://www.google.com
https://google.com
google.com
www.google.com
Try this instead:
function validateURL(url) {
var urlregex = new RegExp("^((?:https?:\/\/)?(?:www\.)?[0-9A-Za-z]+\.[0-9A-Za-z]+)$");
return urlregex.test(url);
}
´
DEMO
http://regex101.com/r/rG8wP9
OR:
function validateURL(url) {
if (/^((?:https?:\/\/)?(?:www\.)?[0-9A-Za-z]+\.[0-9A-Za-z]+)$/im.test(url)) {
return true;
} else {
return false;
}
}
EXPLANATION:
^ assert position at start of a line
1st Capturing group ((?:https?:\/\/)?(?:www\.)?[0-9A-Za-z]+\.[0-9A-Za-z]+)
(?:https?:\/\/)? Non-capturing group
Quantifier: Between zero and one time, as many times as possible, giving back as needed [greedy]
http matches the characters http literally (case sensitive)
s? matches the character s literally (case sensitive)
Quantifier: Between zero and one time, as many times as possible, giving back as needed [greedy]
: matches the character : literally
\/ matches the character / literally
\/ matches the character / literally
(?:www\.)? Non-capturing group
Quantifier: Between zero and one time, as many times as possible, giving back as needed [greedy]
www matches the characters www literally (case sensitive)
\. matches the character . literally
[0-9A-Za-z]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
0-9 a single character in the range between 0 and 9
A-Z a single character in the range between A and Z (case sensitive)
a-z a single character in the range between a and z (case sensitive)
\. matches the character . literally
[0-9A-Za-z]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
0-9 a single character in the range between 0 and 9
A-Z a single character in the range between A and Z (case sensitive)
a-z a single character in the range between a and z (case sensitive)
$ assert position at end of a line
g modifier: global. All matches (don't return on first match)
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
what is wrong with regexp?
This part of regexp:
([0-9A-Za-z]+\.)
can't be matched with "google.com" in your example. But it matches with wrong domain addresses like google. Something like this:
(?:[0-9A-Za-z]+\.)+[A-Za-z]{2,}
is more correct and flexible.
Several things not working in this regexp. For instance nothing happen after the period at the end. Also never need {1} as every expression matched once by default. Main problem is the | because the branches are not inside () so after each | the match restart completely
This is your regexp cleaned up. For instance pulling things into groups, see the | inside ().
isMatch = (/^(?:(?:https?|ftp):\/\/)?(?:www\.)?[0-9a-z]+\.[a-z]+/im.test(url))

Regular expression for numbers and one decimal

I can't seem to get a simple regular expression to work. Here's what I have at the moment:
$(".Hours").on('input', function (e) {
var regex = /^\d+(\.\d{0,2})?$/g;
if (!regex.test(this.value)) {
if (!regex.test(this.value[0]))
this.value = this.value.substring(1, this.value.length);
else
this.value = this.value.substring(0, this.value.length - 1);
}
});
I need the user to be able to only enter numbers and one decimal (with only two numbers after the decimal). It's working properly now, with the exception that a user cannot start with a decimal.
Acceptable:
23.53
0.43
1111.43
54335.34
235.23
.53 <--- Not working
Unacceptable:
0234.32 <--- The user can currently do this
23.453
1.343
.234.23
1.453.23
Any help on this?
Updated answer:
RegExp -
^(?:0|[1-9]\d+|)?(?:.?\d{0,2})?$
Explanation at regex101:
Original answer:
fiddle Demo
RegExp -
^(\d+)?([.]?\d{0,2})?$
Explanation
Assert position at the beginning of the string «^»
Match the regular expression below and capture its match into backreference number 1 «(\d+)?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below and capture its match into backreference number 2 «([.]?\d{0,2})?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match the character “.” «[.]?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d{0,2}»
Between zero and 2 times, as many times as possible, giving back as needed (greedy) «{0,2}»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
Here is a suggestion : /^((\d|[1-9]\d+)(\.\d{1,2})?|\.\d{1,2})$/.
Allows : 0, 0.00, 100, 100.1, 100.10, .1, .10...
Rejects : 01, 01.1, 100., .100, ....
Would this meet your needs:
var regex = /^\d+([.]?\d{0,2})?$/g;
Your regex:
var regex = /^\d+(\.\d{0,2})?$/g;
What you need:
var regex = /^\d*(\.\d{1,2})?$/;
You were requiring at least one digit before the decimal (\d+). I have also changed it so if you include a decimal, there must be at least one digit after it.
This one will force you to add digit after decimal separator :
^\d+([.]\d)?$
Example :
123 => true
=> false
123.1 => true
123.12 => false
123.. => false
if you want more digit; 3 for ex; make sure you fix min to "1" for digit after dicimal
^\d+([.]\d{1,3)?$

Categories