Phone validation - javascript

Near the end of my project and I require some assistant.I need a regex code to validate the phone number. If the phone number is not empty, validate that the phone number is in one of the following formats:
‘xxx–xxx-xxxx’ – 10 digits with two dashes where the first dash is between the third and fourth digits and the second dash is between the sixth and seventh digits.
‘xxxxxxxxxx’’ – all 10 digits, or,
‘(xxx)xxxxxxx’’ – 10 digits with the first three digits being enclosed by parentheses.
‘(xxx)–xxx-xxxx’ – 10 digits with the first three digits being enclosed by parentheses, and there is a dash between the sixth and seventh digits.
Also it needs to provide an alert if the phone number is not in the required format. All formats must be accepted by the validation or else it fails.
My issue is that I made an attempt to do this with regular expression because I feel that this is easy for me. I’m not an experience programmer at all so write codes have never been my thing and my question is there a RegExpression that covers all the formats at once and still able to give me an alert if no number is selected and the user not using one of the required formats.
Here is my current code but it does not cover the four formats.
var phone = document.myForm.phone.value;
if (!/^\d{3}-\d{3}-\d{4}$/.test(document.myForm.phone.value)) {
alert("Please enter the correct phone format ");
This code only covers xxx-xxx-xxxx. Is it possible to cover all formats with this kind of code? Please it must be regex starting with “var phone” like I have in my code example or it tends to get messy.
Thanks in advance

Regex can get pretty tricky if you're pretty new to it. Anytime I need to test some regex/find help I use Regexr. Pretty neat little sandbox for testing regex.
As for your question I think this will work nicely.
var phone = [
'555-555-5555',
'(555)-555-5555',
'(555)555-5555',
'5555555555',
'(555)5555555'
];
for ( var i = 0; i < phone.length; i++ ) {
if ( !/(?:\d{1}\s)?\(?(\d{3})\)?-?\s?(\d{3})-?\s?(\d{4})/.test(phone[i]) ) {
console.log(phone[i]+': invalid');
}
}
Also I did use one of the community regex snippets from the site I linked above. Not taking credit for that.
Your regex itself is almost there. If you want to make something 'optional' use ? before whatever you want to make optional. In this case ( ) should be optional so \(?\d{3}\)? would make the ( ) optional but still force \d{3} to be required.

Instead of making one complex/giant RegExp, why not test multiple simpler RegExp's?
var phones = [
'0123456789',
'012-345-6789',
'(012)3456789'
],
tests = [
/^\d{3}-\d{3}-\d{4}$/,
/^\d{10}$/
],
pre = document.getElementById('out');
phones.forEach(function (phone) {
pre.textContent += phone + ' : ';
var pass = tests.some(function (test) {
return test.test(phone.toString());
});
if (pass) {
pre.textContent += 'pass';
} else {
pre.textContent += 'fail'
}
pre.textContent += '\n';
});
<pre id="out"></pre>
I've only included 2 rules in this example, but you can see it will be much easier to maintain, add/remove rules.

(?:^\d{3}-\d{3}-\d{4}$)|(?:^\(\d{3}\)\d{3}-\d{4}$)|(?:[0-9]{10})
This will cover the three examples you mentioned.
(If you build each example by itself then concatenate with a pipe (equivalent to 'or') you can add more...)
However if you are going to do a catch for ALL Valid Phone Number Formats, this will get quite lengthy. At that point i would suggest a different approach.

Related

Regex for contact number that does/doesn't start with a +

I have tried to create a basic South African contact number regex. Its not working though. The rules are simple.
10 digits or
11 digits if it starts with a +
Examples:
0119879874
0731231234
+27731231234
+27123456789
It must match only digits and length.
My attempt: [+\d]\d{9}\d{0,2}
I tested on the site https://regex101.com/ and it looked like it worked but not when i test it with /[+\d]\d{9}\d{0,2}/.test('12345gjhf6789123456')) then i get a true value.
You should specify ^ - begin of the string and end $
and
/^(\+\d)?\d{10}$/.test('12345gjhf6789123456'))
Rather than use a regex that will not provide any error messaging and is difficult to read (and maintain), I would suggest a simple validation function that lays out the rules explicitly:
function validate(num) {
if (num[0] === '+') {
return num.length === 11;
} else {
return num.length === 10;
}
}
This has a few advantages, including:
faster than a regex
easier to comment and expand later
can be replaced with a full blown predicate library or just an array of rules

Allowing a dash in this regex

I'm using this Wordpress plugin called 'Easy contact form' which offers standard validation methods.
It uses the following regex for phone numbers:
/^(\+{0,1}\d{1,2})*\s*(\(?\d{3}\)?\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/
Just now it allows the following formats (maybe more):
0612345678
+31612345678
But I want it to allow +316-12345678 and 06-12345678 also ... Is this possible? If so, how?
Thanks in advance!
You can use a less complex regex :
^\+?\d{2}(-?\d){8,9}$
This regex allows a + at the beginning of the phone number, then matches two digits, and after that, digits preceded (or not) by a -, for a total of 10 or 11 digits.
Now you can adapt it if the initial + is only for 11-digits phone numbers :
^\+?\d{3}(-?\d){9}|\d{2}(-?\d){8}$
My regex allow you to use - every digit. If that's an issue, it can be changed :
^\+?\d{3}(-?\d{2}){4}|\d{2}(-?\d{2}){4}$
I think this last regex will answer your needs, and it's quite simple !
When you figure out what patterns you actually want to allow and not allow. Then fill them out in this function and if the statement returns true you have your regex.
var regex = /^\+?\d{3}(-?\d{2}){4}|\d{2}(-?\d{2}){4}$/; //this is your regex, based on #Theox third answer
//allowed patterns
['0612345678', '+31612345678', '+316-12345678', '06-12345678'].every(function(test) {
return regex.exec(test) !== null;
}) &&
//disallowed patterns, none right now
[].every(function(test) {
return regex.exec(test) === null;
});

Regex character sets - and what they contain

I'm working on a pretty crude sanitizer for string input in Node(express):
I have glanced at some plugins and library, but it seems most of them are either too complex or too heavy. Therefor i decided to write a couple of simple sanitizer-functions on my own.
One of them is this one, for hard-sanitizing most strings (not numbers...)
function toSafeString( str ){
str = str.replace(/[^a-öA-Ö0-9\s]+/g, '');
return str;
}
I'm from Sweden, therefore i Need the åäö letters. And i have noticed that this regex also accept others charachters aswell... for example á or é....
Question 1)
Is there some kind of list or similar where i can see WHICH charachters are actually accepted in, say this regex: /[^a-ö]+/g
Question 2)
Im working in Node and Express... I'm thinking this simple function is going to stop attacks trough input fields. Am I wrong?
Question 1: Find out. :)
var accepted = [];
for(var i = 0; i < 65535 /* the unicode BMP */; i++) {
var s = String.fromCharCode(i);
if(/[a-ö]+/g.test(s)) accepted.push(s);
}
console.log(s.join(""));
outputs
abcdefghijklmnopqrstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³
´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö
on my system.
Question 2: What attacks are you looking to stop? Either way, the answer is "No, probably not".
Instead of mangling user data (I'm sure your, say, French or Japanese customers will have some beef with your validation), make sure to sanitize your data whenever it's going into customer view or out thereof (HTML escaping, SQL parameter escaping, etc.).
[x-y] matches characters whose unicode numbers are between that of x and that of y:
charsBetween = function(a, b) {
var a = a.charCodeAt(0), b = b.charCodeAt(0), r = "";
while(a <= b)
r += String.fromCharCode(a++);
return r
}
charsBetween("a", "ö")
> "abcdefghijklmnopqrstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö"
See character tables for the reference.
For your validation, you probably want something like this instead:
[^a-zA-Z0-9ÅÄÖåäö\s]
This matches ranges of latin letters and digits + individual characters from a list.
There is a lot of characters that we actually have no idea about, like Japanese or Russian and many more.
So to take them in account we need to use Unicode ranges rather than ASCII ranges in regular expressions.
I came with this regular expression that covers almost all written letters of the whole Unicode table, plus a bit more, like numbers, and few other characters for punctuation (Chinese punctuation is already included in Unicode ranges).
It is hard to cover everything and probably this ranges might include too many characters including "exotic" ones (symbols):
/^[\u0040-\u1FE0\u2C00-\uFFC00-9 ',.?!]+$/i
So I was using it this way to test (have to be not empty):
function validString(str) {
return str && typeof(str) == 'string' && /^[\u0040-\u1FE0\u2C00-\uFFC00-9 ',.?!]+$/i.test(str);
}
Bear in mind that this is missing characters like:
:*()&#'\-:%
And many more others.

Javascript regexp using val().match() method

I'm trying to validate a field named phone_number with this rules:
the first digit should be 3 then another 9 digits so in total 10 number example: 3216549874
or can be 7 numbers 1234567
here i have my code:
if (!($("#" + val["htmlId"]).val().match(/^3\d{9}|\d{7}/)))
missing = true;
Why doesnt work :( when i put that into an online regexp checker shows good.
You should be using test instead of match and here's the proper code:
.test(/^(3\d{9}|\d{7})$/)
Match will find all the occurrences, while test will only check to see if at least one is available (thus validating your number).
Don't get confused by pipe. Must end each expression
if (!($("#" + val["htmlId"]).val().match(/^3\d{9}/|/\d{7}/)))
missing = true;
http://jsfiddle.net/alfabravoteam/e6jKs/
I had similar problem and my solution was to write it like:
if (/^(3\d{9}|\d{7})$/.test($("#" + val["htmlId"]).val()) == false) {
missing = true;
}
Try this, it's a little more strict.
.match(/^(3\d{9}|\d{7})$/)

Test Password with Regex

I want to test a passwprd which must have at least 6 characters and 1 number in it. What regex string I can use with JS to get this done?
UPDATED
I forgot to write it must have at least 6 alpha characters and 1 numeric character but it should also allow special characters or any other character. Can you please modify your answers? I greatly appreciated your responses
This does smell a little like a homework question, but oh well. You can actually accomplish this concisely using a single regular expression and the "look ahead" feature.
/(?=.{6}).*\d.*/.test("helelo1")
The first bit in the brackets says "peek ahead to see if there's 6 characters". Following this we check for any number of characters, followed by a number, followed by any number of characters.
It is even possible to accomplish your goal in a single regex without having the faculty of look ahead... It's just a little hard to look at the solution and not wince:
new RegExp("[0-9].....|" +
".[0-9]....|" +
"..[0-9]...|" +
"...[0-9]..|" +
"....[0-9].|" +
".....[0-9]").test("password1")
Try this:
password.match(/(?=.*\d).{6}/);
More info here.
As far as I know this is best done with a combination of string functions and regex:
if( myPass.match(/[a-zA-Z]/).length >= 6 && myPass.match(/\d/g).length ) {
// Good passwords are good!
}
EDIT: Updated to include the new stipulations. Special characters are allowed, but not required.
if (/.{6,}/.test(password) && /\d/.test(password)) {
// success
} else {
// fail
}
/^(?=[\w\d]{6,}$)(?=.*\d)/.test(password)
requires 6 or more characters (letters, numbers or _)
requires at least one digit
won't allow any special characters
This is a js to check password,
it checks min 7 chars, contains 1 Upper case and 1 digit and 1 special character and must not contain a space, hope it will help you.
pwLength = this.value.length;
if (pwLength > 7 && pwLength < 21) {
charLengthIcon.removeClass("fail").addClass("pass");
}
else charLengthIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[A-Z]/g)) {
capLetterIcon.removeClass("fail").addClass("pass");
}
else capLetterIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[0-9]/g)) {
numberIcon.removeClass("fail").addClass("pass");
}
else numberIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[##$%!$&~*^(){}?><.,;:"'-+=|]/g)) {
splcharIcon.removeClass("fail").addClass("pass");
}
else splcharIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[\s/]/g)) {
whiteSpce.removeClass("pass").addClass("fail");
}
else whiteSpce.removeClass("fail").addClass("pass");
confirmPW();
});

Categories

Resources