Auto correct phone format input - javascript

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...

Related

multiple regexp in one input

hi i have one input type tel for mobile number and like use pattern for number format like this
938 119 1229
but when i use type tel i can use word in input
i try use the two regex in one input but i don't know how :
function mobileNumInput(input){
var regex = /[^0-9]/g; //for digit only
input.value=input.value.replace(/^(\d{3})(\d{3})(\d+)/, '$1 $2 $3'); //for space between numbers
input.value=input.value.replace(regex)
}
and html :
<input type="tel" name="phone" placeholder="912 000 0000" maxlength="12" min="0" max="9" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" onkeyup="mobileNumInput(this)" autofocus>
this is my placeholder:
enter image description here
i want this format :
enter image description here
But I don't want to use word like this :
enter image description here
sorry my english is bad
I'm guessing that you want to do the following:
Remove all non-numeric characters from the phone number.
Example: convert '(111)-174-1234' to '1111741234'
Add spaces in the correct location to the resultant number.
Example: convert '1111741234' to '111 174 1234'
If my assumptions about the purpose of this code are true, your code had two mistakes:
You put step #1 after step #2.
This led to an input '(111)-174-1234' having the regex (#2) running the following replacement: .replace(/^(\d{3})(\d{3})(\d+)/, '$1 $2 $3')
The above snippet of code only works on pure numbers. It does not recognize '(111)-174-1234' as containing any matches to /^(\d{3})(\d{3})(\d+)/, so no replacements are made. In other words, after line 3 of your code runs, input.value has likely not changed.
The solution to this is simply to switch line 3 and 4 in your program.
In step #1, you used .replace(regex) instead of .replace(regex,'').
This is just a String method technicality: String.prototype.replace accepts a regex and a string to replace it. Leaving the second parameter empty is the same as setting the second parameter as undefined.
An example is that "Hello world".replace(/l/g) is the same as "Hello world".replace(/l/g,undefined). The result of both of these snippets is "Heundefinedundefinedo world". You can gain the desired behavior by using "Hello world".replace(/l/g,'') instead. This will return "Heo world".
I put my fixes into a revised version of your code:
function mobileNumInput(input){
var regex = /[^0-9]/g; //for digit only
input.value=input.value.replace(regex, ''); // Step #1 (remove non-digits)
input.value=input.value.replace(/^(\d{3})(\d{3})(\d+)/, '$1 $2 $3'); //Step #2 (add spaces to valid phone number)
}
Here is a slightly further modified version of your code with one test:
function mobileNumInput(input){
input.value=input.value
.replace(/[^0-9]/g, '')//Remove all non-digits
.replace(/^(\d{3})(\d{3})(\d+)/, '$1 $2 $3'); //Add spaces to the only-digit number
}
function test(){
var testInputElement=document.createElement("input");
testInputElement.value='(123)-[456} - 7890';//Horribly formatted phone number
mobileNumInput(testInputElement);
console.log(testInputElement.value);
}
test();
//123 456 7890

Regex for coercing input for phone number in javascript

I have an input for a phone number in french format
The input accepts two kinds of format, so i can input this:
0699999999
+33699999999
no check is done for the length of the number.
The table in database, the field is of varchar 12, i can have shorter input though.
The constraints: input contains only digits from 0 to 9, optional '+' sign accepted only if it starts the string, not after.
Currently i am in Angular with a directive, in that directive the heart is this expression :
var transformedInput = inputValue.replace(/[^0-9]/g, '');
i want the optional leading '+' sign, how can i achieve this?
thanks.
You could make the plus sign optional:
if (/\+?\d*/.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
subject is the text you want to check. \+ makes the plus sign a literal and the questionmark makes it optional.
If you just want to check wether ther is a plussign drop the questionmark. But if that is your goal don't use a regex. That is too much overhead. Simply get the first charactor of the trimmed string and check for the plus.
Change it to
var transformedInput = inputValue.replace(/[^0-9\+]/g, '').replace(/(.)\+/g, '$1');
Note - this will NOT add a + unless there is already a + in the input
What it does is
Do not remove the + symbol on the first replace
Remove every + symbol that is preceded by some character on the 2nd replace

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>

Regex to validate 3 specific forms of a phone number

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.

Phone Number Validation Javascript

I want users to allow only phone numbers in following format
xxx-xxx-xxxx or xxxxxxxxxx all digits only . Can some one suggest a regular expression to do this ?
Something like this:
\d{3}-\d{3}-\d{4}|\d{10}
While general phone number validation is a larger problem than what you're trying to solve, I'd do the following:
var targ=phone_number_to_validate.replace(/[^\d]/g,''); // remove all non-digits
if(targ && targ.length===10) {
// targ is a valid phone number
}
Doing it this way will validate all of the following forms:
xxxxxxxxxx
xxx-xxx-xxxx
(xxx) xxx-xxxx
etc.
Also, to trivially check for a valid U.S. area code, you can use:
if(targ.matches(/^[2-9]\d{2}/)) // targ is a valid area code
Again, this is a trivial check. For something a little more rigorous, see this List of Legal US Area Codes.
See also A comprehensive regex for phone number validation
Use this :
/^(1-?)?(([2-9]\d{2})|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/
var rx=/^\d{3}\-?\d{3}\-?\d{4}$/;
if(rx.test(string)){
//10 diget number with possible area and exhange hyphens
}
else //not
The following regular expression can be used to validate defined and operational (as of 6/2011) telephone area codes within the U.S.:
var area_code_RE=
'(2(?:0[1-35-9]|1[02-9]|2[4589]|3[1469]|4[08]|5[1-46]|6[0279]|7[068]|8[13])'+
'|3(?:0[1-57-9]|1[02-9]|2[0139]|3[014679]|47|5[12]|6[019]|8[056])'+
'|4(?:0[126-9]|1[02-579]|2[3-5]|3[0245]|4[023]|6[49]|7[0589]|8[04])'+
'|5(?:0[1-57-9]|1[0235-8]|[23]0|4[01]|5[179]|6[1-47]|7[01234]|8[056])'+
'|6(?:0[1-35-9]|1[024-9]|2[0368]|3[016]|4[16]|5[01]|6[012]|7[89]|8[29])'+
'|7(?:0[1-4678]|1[2-9]|2[047]|3[1247]|4[07]|5[47]|6[02359]|7[02-59]|8[156])'+
'|8(?:0[1-8]|1[02-8]|28|3[0-25]|4[3578]|5[06-9]|6[02-5]|7[028])'+
'|9(?:0[1346-9]|1[02-9]|2[0578]|3[15679]|4[0179]|5[124679]|7[1-35689]|8[0459])'+
')';

Categories