Regular Expression for Phone Number - javascript

I need a Javascript RegEx through which I can validate phone number. RegEx should handle following criteria
It should only consist of numbers ( ) + and -
Count of + should not exceed 1
Count of - should not exceed 4
There must be only one pair of ()
If '(' is present in phone number then ')' must be present.
Thanks for the help!
Hussain.

Try this:
function valid_phone_number(ph) {
var regex = /^(?!([^-]*-){5})(\+\d+)?\s*(\(\d+\))?[- \d]+$/gi;
return regex.test(ph);
}
I'm new to regular expressions, so please be nice. :-)

Related

Using regex to validate given password has alphabetic, numeric, and special characters not

I am trying to use regex in JavaScript to verify if a given password has alphabetic, numeric, and a special character. However, everything I have tried doesn't work
I have tried using
/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!#"#%$&])[A-Za-z0-9!#"#%$&]{8,30}$/gm
and creating separate regex variables for alphabetic, numeric, and special characters:
let alpha = /^[A-Za-z]+$/i
let numer = /^[0-9]+$/i
let special = /^[!##$%^&*(),.?;":{}|<>']/i
Picture of My Code
When I log the password.match(regex) to the console I always see null
Try this:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$
This is from a post a long time ago. There are probably others as well. A simple search of SO will find more examples.1
Here is a visualisation of the regular expression:
Debuggex Demo
I would personally go for separate regexes, the issue with your current regexes is that you have ^ at the start and $ at the end. Which means that the password must only contain [A-Za-z] from start to finish. Then you check if the password only contains [0-9] from start to finish.
const regexes = {
alpha: /[A-Za-z]/,
number: /[0-9]/,
special: /[!##$%^&*(),.?;":{}|<>']/,
length: /^.{8,30}$/
};
["dgXHUYuDdp", "zMv4qQfZj3", "4JXyrsq!J0", "a5Z!"].forEach(password => {
let valid = Object.values(regexes).every(regex => password.match(regex));
console.log(
"password: " + JSON.stringify(password) + "\n" +
"valid: " + valid
);
});
While I suspect it may be possible to write a regex which will do position/seuqnce independent matching, my head hurts just thinking about. So even if I could work out a way of doing it, I would not implement it - code needs to be readable and parseable by human beings. Looking at what you have presented here, I think I'm a lot more familiar with regexes than you are - so even more reason not to do this.
Your alpha / numer / special regexes will only match a string containing letters, numbers or special characters, not a mixture. If you change them thus, then you can check for a match of all three (and escape the meta characters in the special regex):
let alpha = /[A-Za-z]/i;
let numer = /[0-9]/;
let special = /[!##$%\^&*(),\.?;":{}|<>\']/;
if (password.match(alpha) && password.match(numer) && password.match(speicial)) {

JavaScript Validate Phone Number Using Regex

Greetings overflowers,
I'm trying to write a regular expression to validate phone numbers of the form ########## (10 digits)
i.e. this is these are cases that would be valid: 1231231234 or 1111111111. Invalid cases would be strings of digits that are less than 10 digits or more than 10 digits.
The expression that I have so far is this:
"\d{10}"
Unfortunately, it does not properly validate if the string is 11+ digits long.
Does anyone know of an expression to achieve this task?
You need to use ancors, i.e.
/^\d{10}$/
You need to anchor the start and the end too
/^\d{10}$/
This matches 10 digits and nothing else.
This expression work for google form 10 digit phone number like below:
(123) 123 1234 or 123-123-1234 or 123123124
(\W|^)[(]{0,1}\d{3}[)]{0,1}[\s-]{0,1}\d{3}[\s-]{0,1}\d{4}(\W|$)
I included the option to use dashes (xxx-xxx-xxxx) for a better user experience (assuming this is your site):
var regex = /^\d{3}-?\d{3}-?\d{4}$/g
window.alert(regex.test('1234567890'));
http://jsfiddle.net/bh4ux/279/
I usually use
phone_number.match(/^[\(\)\s\-\+\d]{10,17}$/)
To be able to accept phone numbers in formats 12345678, 1234-5678, +12 345-678-93 or (61) 8383-3939 there's no real convention for people entering phone numbers around the world. Hence if you don't have to validate phone numbers per country, this should mostly work. The limit of 17 is there to stop people from entering two many useless hyphens and characters.
In addition to that, you could remove all white-space, hyphens and plus and count the characters to make sure it's 10 or more.
var pureNumber = phone_number.replace(/\D/g, "");
A complete solution is a combination of the two
var pureNumber = phone_number.replace(/\D/g, "");
var isValid = pureNumber.length >= 10 && phone_number.match(/^[\(\)\s\-\+\d]{10,17}$/) ;
Or this (which will remove non-digit characters from the string)
var phoneNumber = "(07) 1234-5678";
phoneNumber = phoneNumber.replace(/\D/g,'');
if (phoneNumber.length == 10) {
alert(phoneNumber + ' contains 10 digits');
}
else {
alert(phoneNumber + ' does not contain 10 digits');
}

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();
});

Regular expression JavaScript

I have modal pop up for adding data, I have to validate textbox using JavaScript regular expression for numeric values only. I want to enter only numbers in text box, so tell me what is proper numeric regular expression for that?
Why not using isNaN ? This function tests if its argument is not a number so :
if (isNaN(myValue)) {
alert(myValue + ' is not a number');
} else {
alert(myValue + ' is a number');
}
You can do it as simple as:
function hasOnlyNumbers(str) {
return /^\d+$/.test(str);
}
Working example: http://jsfiddle.net/wML3a/1/
^\d+$
of course if you want to specify that it has to be at least 4 digits long and not more than 20 digits the pattern would then be => ^\d{4,20}$

Categories

Resources