Regex to validate 3 specific forms of a phone number - javascript

So I am trying to write code that will evaluate if a phone number is valid in one of three ways.
The first is the form xxx-xxx-xxxx, the second is (xxx) xxx-xxxx, and the third is xxxxxxxxxx.
Here's my regular expression:
if (/^\d{3}-\d{3}-\d{4}$/.test(phoneVal) || /^\d{10}$/.test(phoneVal) || /^\(\d{3}\) \d{3}-\d{4}$/.test(phoneVal)) {
return true;
}
However whenever I put in what I would consider to be a valid phone number, it trips up this regular expression, and gives the error:
else {
alert("Please put in a correct phone number");
return false;
}

When running this: phoneVal = document.getElementById("phone");
alert(phoneVal); I get: [Object HTML InputElement]
You're getting the element rather than its value. Use the value property:
phoneVal = document.getElementById("phone").value;

Here's a tested function which meets your requirements:
// Validate 10 digit US phone number in one of three specific formats.
function validatePhoneNumber(text) {
/* # Validate US phone number in one of three specific formats.
^ # Anchor to start of string.
(?: # Group alternatives.
[0-9]{3}-[0-9]{3}-[0-9]{4} # Either xxx-xxx-xxxx
| \([0-9]{3}\)[ ][0-9]{3}-[0-9]{4} # or (xxx) xxx-xxxx
| [0-9]{10} # or xxxxxxxxxx
) # End group of alternatives.
$ # Anchor to end of string.
*/
var re = /^(?:[0-9]{3}-[0-9]{3}-[0-9]{4}|\([0-9]{3}\)[ ][0-9]{3}-[0-9]{4}|[0-9]{10})$/;
return re.test(text);
}
That said, as others have pointed out, you should allow users to input a more loosely defined number. See my answer to your other (nearly identical) question which is more forgiving.

I think when it comes to phone numbers you need to give you're users freedom to write the number in one of their own prefered format.
The regex below matches ##########, ###.###.####, ###-###-####, ### ### ####, (###) ### ####, (###)-###-#### and many more combinations.
if(/\(?\b[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}\b/.test(phoneVal))
{
return true;
} else
return false;
}

For phone numbers, I tend to strip out any characters that's not A-Z, 0-9, and then make sure the result is numeric, and 10 digits long. Some people use periods, dashes, brackets, spaces, etc. 1-23--4..5#678_9%0 would be a valid phone number, but when I store it in the database, I normalize it to 1234567890, and then when presenting it back, I format it myself in the format of my own choosing, such as 123-456-7890.

Related

Javascript regex formatter for now allowing a number having , and . at the same time

i'm having an amount input field.
This field must accept only number. For this purpose i use this regex expression:
amount.toString().match(/[a-z]/i). The field also allows decimal seperator with . or , For example the number 1004.23 or 1004,23 is allowed. But if the user enters a number with thousands and decimal seperators this case must be prevented. For example a number like 1,000.14 must not be allowed. How to implement this?
You can require only digits, then optionally a single , or . followed by digits (so you don't end up with one at the end):
/^\d+(?:[,.]\d+)?$/
(The (?:....) is a non-capturing group, the entire contents of which are optional.
Then use that with test:
if (/^\d+(?:[,.]\d+)?$/.test(amount)) {
// It's good
} else {
// It's not
}
No need for toString, test will do that if appropriate.
Example:
function check(str) {
return /^\d+(?:[,.]\d+)?$/.test(str);
}
function test(str) {
console.log(str, "- Allowed:", check(str));
}
test("1004.23");
test("1004,23");
test("1004");
test("1004.");
test(",1004");
test("1,000.14");
Of course, you still won't know whether they intend , or . to be a decimal or thousands separator.
It seems that your logic is effectively allowing any number with at most one decimal or comma:
^\d+(?:[.,]\d+)?$

Validate R1:C1 to R2:C2 notation in google sheets

I need to validate range R1:C1-R2:C2 range
I tried with,
function isValid(rc) {
if (rc)
if (rc.trim() === "") return false;
var isPattern = /^[0-9]+:[0-9]+-[0-9]+:[0-9]+$/.test(rc);
if (!isPattern) return false;
return ((rc));
}
But the above code also takes 9:9-0:0 or 0:0-0:0
UPDATE:
How do I check whether the given range after a numeric validation at client side is correct in the server side. Because, at server side range may be invalid.
You need to check that there are some alphabetic characters, then numeric characters - this is how to match a field: [a-z]+\d+. It will match some characters, then some numbers. E.g. a1, ASD34. It won't match 12 or sab though.
If you put all together, you get this regex:
/^[a-z]+\d+:[a-z]+\d+\s*-\s*[a-z]+\d+:[a-z]+[0-9]+$/i
Explanation:
/../i matches case insensitively, so it's enough to specify [a-z], no need to type [a-zA-Z]
this matches a field: [a-z]+\d+, like R1 or B12. It won't match 12 or AB
\s*-\s* tolerates spaces around the dash
so we got: field:field-field:field and that's what you want.
You can play with this regex demo.
Checking if the values are actually okay, it takes more than a regex. You'll have to split the code by the dash and the colons and compare the values.

Regex for password must be 6 to 8 characters long containing at least 3 alphabets, 2 number, no special character, Must not contain the sequence ‘pas’

I am trying to write a regular expression to validate a password which must meet the following criteria:
a. Password must be 6 to 8 characters long, contain at least 3 alpha and 2 numeric characters and no special characters.
b. Must not contain the sequence ‘pas’.
What I've tried so far:
/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8})$/
I suggest you to not use only one regex, because that way the users would not know why their password are failing.
I would do something like this:
function checkPassword (pass) {
pass = {
text: pass,
length: pass.length,
letters: pass.match(/[a-z]/gi).length,
digits: pass.match(/[0-9]/g).length,
contains_pas: !!pass.match(/pas/i) // <- will result true/false
}
pass.specials = pass.length - pass.letters - pass.digits;
// here you can use your logic
// example:
if (pass.contains_pas) {
alert('The password can not contains "pas".');
}
return pass; // you can return or not
}
Hope it helps.
You can try this:
([[a-zA-Z]{3,}+[0-9]{2}])^((?!pas).)$
It works only if user enters consecutive alphabets and then numbers. So, its a partial solution to this problem.
For the stated problem, I would suggest not to use reg-ex. As, reg-ex validates a particular order, you should incorporate separate checks for each test.

Auto correct phone format input

I'm trying to auto format an input on HTML with javascript, and it is almost done, i need the format to be xxx-xxx-xxxx but and I have this code
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
as youy can see it will just auto format xxx-xxx-xxx but I need to be 4 digits at the end
any sugestions?
Try this regexp:
'1234567890'.replace(/(\d{3}(?!\d?$))\-?/g, '$1-'); // 123-456-7890
The part (?!\d?$) is a negative lookahead. It allows regular expression to match three digits only if they are not followed by another number (4th) (but not necessarily ?) at the end of the string $.
So it will not match 789 group because it's followed by 0$.
Or simply : .replace(/(\d{3})(\d{3})(\d{4})\-?/g,'$1-$2-$3');
Sample code to help you out:
var phone = '(555) 666-7777';
// First clean your input
phone = phone.replace(/[^\d]/g, '');
// Check the length of the phone
if(phone.length == 10){
// Now we can format the phone
phone = phone.substring(0,3)+'-'+phone.substring(3,6)+'-'+phone.substring(6, 10);
// Optionally
//phone = phone.replace(/(\d{3})(\d{3})/, '$1-$2-');
}
else {
// whatever you want to tell the user
}
there seems to be a bug in the "replace" regex's above. enter a 10 digit number and you see it formatted correctly (e.g. "(123) 456-7890"). Then, select the contents of the field (double or triple click it) and overtype the value. You'll see the first two digits get transposed. So if you enter 1 2 3, you'll see 2 1 3...

How can I implement a live Javascript Regex for phone numbers?

I have a text box and it says "Phone:" as the standard here for phone number is (XXX)-XXX-XXXX
I'd like to have a javascript that automatically puts my numbers into that format if it's not in that format, so if you typed 9993334444 then it would change it automatically on the fly as I'm typing to (999)-333-4444 I have looked around Google for Javascript Phone Regex to no success, maybe a Regex isn't what I'm looking for?
you want to add an onkeyup event with a regex like
this.value = this.value.replace(/^\(?([0-9][0-9][0-9]){1}\)?-?([0-9][0-9][0-9][0-9]){1}-?([0-9][0-9][0-9]){1}$/, '($1)-$2-$3');
Check out http://jsfiddle.net/R8enX/
/ means start/end a regex string
^ means start of matching string
$ means end of matching string
? means 0 or 1 instances (make braces and dashes optional)
[0-9] means any single digit
(x){1} tags x as an expression that we can reference in the replacement with a $ sign
EDIT: realized I missed a digit on the last group of numbers, the jsfiddle will only work (properly) with 3 digits in the last group
To build somewhat on #Andrews answer you can check for a valid (local)phone number via this method. If the number is shorter or larger than 10 digits, it collapses back into an invalid number
-
<input type="text" onBlur="localNumber(this.value)"/>
<div id="output"></div>
-
<script>
var localNumber = function(str){
repl = str.replace(/^([0-9]{3})([0-9]{3})([0-9]{4})$/, "($1)-$2-$3");
outp = document.getElementById('output');
if( repl.match(/\W/) )
{
outp.innerHTML = repl;
}
else
{
outp.innerHTML = 'Invalid number for this region';
}
}
</script>

Categories