Regex for validating telephone number - javascript

I'm new to programming. How should a regular expression look like, to match the following requirements:
String has to start with "+"
After that + only numbers and blanks in any combination are allowed
Example for a valid number: +49 1223 3447 554 9
I'm trying to validate a String telephone field with Java Script.
Thanks!

For validation of phone I use either feature
function isValidPhone(sendersPhone) {
var pattern = new RegExp(/\d\(\d{3}\)-\d{3}-\d{2}-\d{2}/);
return pattern.test(sendersPhone);
}
Or if you are using jquery, it is often more convenient to use the mask, for example
Masked Input Plugin for jQuery https://github.com/digitalBush/jquery.maskedinput
Or for angular.js - angular ui-mask (https://github.com/angular-ui/ui-mask)

function checkPhone(str) {
return str.match(/^\+[0-9\s]+/) ? true : false;
};
var phone = "+49 1223 3447 554 9";
console.log('checkPhone', phone, checkPhone(phone));
even if this regexp satisfy your request, I don't think it's enough to validate phone number, it should be at least 5 digits without counting spaces, check the link provided by #ndn

Related

Not able to match the RegExp in JavaScript even it is matching in QuickRex

Not able to match the regular expression in my JavaScript code which I have written for form validation.
I wanted to validate my form field which is password using RegExp [[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]
My Validations on password is
- Should contain 10 characters including digit
- At least one uppercase letter should be there
- Only # should be used as special character
But the same is working with [0-9a-zA-Z#]{10} but not with [[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]
var regexpassword=/[[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]/
if(!regexpassword.test(password.value)){
alert("Enter valid password")
password.focus();
return false
}
NOTE: The password that I have entered is Welcome#67
It should not give the alert as "Enter valid password"
Best I can tell, the regex you provided, is matching exactly 1 character. the [] operator indicates "any of what is inside". But the only place you are indicating "multiple times" is the [A-Z]{1,8}. Also, as #Pointy mentioned, I don't think you can nest square brackets. Even if you can, it is somewhat redundant.
Your regex is being interpreted as follows:
1. Look for [ or the numbers 0 through 9 between 0 and 8 times in a row
2. Followed precisely by the lowercase letters a through z between 0 and 8 times in a row
3. Followed precisely by the uppercase letters A through Z between 1 and 8 times in a row
4. Followed precisely by a single #
5. Followed precisely by a single ]
This leads to matching strings like (but not limited to):
[A#]
0A#]
9aaaaaaaZ#]
[0123456abcdefghABCDEFGH#]
[[[[[[[[Q#]
[[[[[[[[azazazazAZAZAZAZ#]
but it will not match Welcome#67.
Is there a way to write a regex that will validate a password with your requirements?
Possibly.
Should you use a single regex to validate your password?
Probably not as the necessary complexity of that regex would make it impractical to maintain when your password requirements change.
Is there a practical, maintainable way to validate passwords?
Certainly! Use multiple regexes to validate the required parts of the password.
Then determine if the needed parts are present and make sure the length is acceptable.
Example:
var hasOnlyValidCharacters = /^[0-9a-zA-Z#]+$/gm.test(password.value);
var hasDigits = /[0-9]+/gm.test(password.value);
var hasUpper = /[A-Z]+/gm.test(password.value);
var hasLower = /[a-z]+/gm.test(password.value);
var hasAtSign = /[#]+/gm.test(password.value); // Technically could be /#+/gm.test(...), but I tend to use character classes every time I'm looking for specific characters.
var isValidPassword = (
password.value.length === 10 // Should contain 10 characters
&& hasOnlyValidCharacters
&& hasDigits // including digit
&& hasUpper // At least one uppercase letter should be there
// && hasLower // Uncomment to require at least one lowercase letter
// && hasAtSign // Uncomment to require at least one #
);
if (!isValidPassword) {
alert("Enter valid password")
password.focus();
return false
}
The [untested code] above should do the trick, and following the patterns established in it, you should be able to easily change your password requirements on a whim.

Number extraction from string using regex working partially

I'm extracting the phone numbers that begin with 9 followed by other 9 digits from tweets using JavaScript.
Here's the regex pattern I am using:
var numberPattern = /^9[0-9]{9}/;
Here's the pattern matching phase:
var numberstring = JSON.stringify(data[i].text);
if(numberPattern.test(data[i].text.toString()) == true){
var obj={
tweet : {
status : data[i].text
},
phone : numberstring.match(numberPattern)
}
//console.log(numberstring.match(numberPattern));
stringarray.push(obj);
The problem is it is working for few numbers and not all. Also, I want to modify the regex to accept +91 prefix to numbers as well and(or) reject a starting 0 in numbers. I'm a beginner in regex, so help is needed. Thanks.
Example:
#Chennai O-ve blood for #arun_scribbles 's friend's father surgery in few days. Pl call 9445866298. 15May. via #arun_scribbles
Your regex pattern seems to be designed to allow a 9 or 8 at the beginning, but it would be better to enclose that choice in parentheses: /^(9|8)[0-9]{9}/.
To allow an optional "+" at the beginning, follow it with a question mark to make it optional: /^\+?(9|8)[0-9]{9}/.
To allow any character except "0", replace the (9|8) with a construct to accept only 1-9: /^\+?[1-9][0-9]{9}/.
And in your example, the phone number doesn't come at the beginning of the line, so the caret will not find it. If you're looking for content in the middle of the line, you'll need to drop the caret: /\+?[1-9][0-9]{9}/.
var numberPattern = /([+]91)?9[0-9]{9}\b/;
Try this regex pattern: [\+]?[0-9]{1,4}[\s]?[0-9]{10}
It accepts any country code with +, a space, and then 10 digit number.

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

How to validate phone number using javascript regular expression?

While i type the phone number in a field after 5 digits put a hypen and continue the digits
after hypen. It allows only 10 digits and hypen.
Output : 90000-00000
Can any one help me how to fix the issue.
Thanks
The ReGex for this is really simple, you should have been able to Google this and work it out for yourself. The RegEx you want is as follows:
^[\d]{5}-[\d]{5}$
Using that with javascript:
var input = "90000-00000";
var valid = /^[\d]{5}-[\d]{5}$/.test(input);
//valid is a boolean: true or false
Here is a working example

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

Categories

Resources