/    Sign up×
Community /Pin to ProfileBookmark

phone number formatting in input

Hi everyone,

I am currently creating a contact form in which there is an input for a phone number.
As I’m French, I want the phone number to match French phone number format: “01 23 45 67 89” (10 digits long written in groups of two separated by spaces).
I want to create a script that applies the changes while the user is typing.

I created [URL=”http://jsfiddle.net/DsWgw/1/”]this function[/URL] which adds the spaces and only allow numbers, but works only if the cursor is at the end of the string (doesn’t allow to insert digit elsewhere). I also noticed that there is a weird behavior if you delete all the digits and type again a phone number: it displays “0 12 34 56 78 “.

I thought the way for the function to do exactly what I want is to insert the digit, then delete all the spaces and finally add spaces at the right place, but actually I am not good at all in algorithmics :/ and I noticed that the function I created is executed before the digit is inserted so it won’t work.

Any idea?

Thanks

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@007JulienJan 27.2014 — It's not a good idea to applies the change while the user is typing !

This is unpleasant and annoying. In addition, this can lead to errors in successive strikes without examination of the results.

Try something like this whit a onblur event (which occurs at the end of the typing)
[CODE]
<body>
<input type="text" id="phn" onblur="frm(this.value)"></div>
<script type="text/javascript">
function frm(n){
if ((m=n.replace(/[^d]+/g,'')).length!=10) {alert("Merci d'entrer un numéro à 1O chiffres.");return}
document.getElementById('phn').value=m.replace(/(d)(?=(d{2})+b)/g,'$1 ');
}
</script>
</body>
[/CODE]

We replace all number followed by an even number of numbers by this number followed by a space. I proposed this method, with three digits, for monetary strings on Jan 4'12 on this stackoverflow page.
Copy linkTweet thisAlerts:
@vwphillipsJan 27.2014 — [CODE]<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<title></title>
<script type="text/javascript" >
<!--
// Form Compendium f20 (07-November-2007)
// Format Number
// by Vic Phillips http://www.vicsjavascripts.org.uk

// Format a number, such as a date or phone number as required.

// Options to verify each input 'onblur'
// or a number of specified inputs on Submit or other event.

// Date formats of mm/dd/yyyy and dd/mm/yyyy
// may be checked for valid day, month and year.

// Time inputs are checked for valid hours and minutes
// and can be formated the 12 hour clock with AM or PM suffix

// There may be as many applications on a page as required.

// Application Notes

// **** Introduction
//
// The format is specified as a string
// and passed to the function 'f20FormatNumber()' on the onkeyup event of a text box
// e.g.
// <input name="" size="10" value="Phone Number" onkeyup="f20FormatNumber(this,'(~~~) ~~~~~~'),'Blur or All';" >
// Parameter 0 may be the FormatNumber input object (this)
// or the unique ID name of the FormatNumber input element.

// The sting charactors '~' will be replaced by the numbers typed in the text box
// Parameter 2 'Blur or All' will dictate if the input is verified on blur or on Submit or other event.
// 'Blur' will verify the input 'onblur'
// 'All' will verify the input on Submit or other event.
// 'BlurAll' will verify the input on both 'blur' and Submit or other event.
// If the parameter is not specified verification will not occur.


// **** Check All
//
// The Check All Function f20CheckAll()
// Calling f20CheckAll() will verify all FormatNumber input which have been initialised and inclue 'All'
// The function will return 'true' if all are correct or 'false' if any are incorrect.

// **** Initilisation
//
// The facility would normally be initialise from the first 'keyup' event of the FormatNumber input
// However it may also be initialise from a <BODY> or window onload event calling function 'f20InitFormatNumber('
// e.g.
// <body onload="f20InitFormatNumber('*ID*','~~/~~/~~~~','All');" >
// where
// *ID* = the unique ID name of FormatNumber input element (string)


// **** Verification of Date
//
// The f20FormatNumber() call requires an additional parmeter
// e.g.
// <input name="" size="15" value="mm/dd/yyyy" style="color:gray;" onkeyup="f20FormatNumber(this,'~~/~~/~~~~','Blur',['mm/dd/yyyy',2000,2008]);" >
// Parameter 4 is an array
// parameter 4 field 0 = the required date format 'mm/dd/yyyy' or 'dd/mm/yyyy' (string)
// parameter 4 field 1 = (optional) the minimum permitted year (digits)
// parameter 4 field 2 = (optional) the maximum permitted year (digits)
//
// If field 1 is omitted the min and max years will default to custonising variables f20MinYear & f20MaxYear


// **** Verification of Time
//
// The f20FormatNumber() call requires an additional parmeter
// e.g.
// <input id="TB3" name="" size="15" value="time" style="color:gray;" onkeyup="f20FormatNumber(this,'~~:~~','Blur',['time',' AM',' PM']);" ><br>
// Parameter 4 is an array
// parameter 4 field 0 = the required date format 'time' (string)
// parameter 4 field 1 = (optional) convert to 12 hour clock AM suffix. (string)
// parameter 4 field 2 = (optional) convert to 12 hour clock PM suffix. (string)


// **** General
//
// There can be any number of applications on a page each with a unique format
//
// All variable, function etc. names are prefixed with 'f20' to minimise conflicts with other JavaScripts
//
// The functional code(3.0 or 4.5K with date and time) is best as an external JavaScript.
//
// Tested with IE6, Mozilla FireFox and Safari


// Customising Variables
var f20InitialColor='gray';
var f20TypingColor='blue';
var f20CompleteColor='black';
var f20WarningColor='RED';
var f20MinYear=1800;
var f20MaxYear=3000;

// Functional Code

// NO NEED to Change
var f20War,f20CkAllCk;
var f20CkAllAry=[];

function f20InitFormatNumber(f20obj,f20format,f20m,f20date){
if (typeof(f20obj)=='string'){ f20obj=document.getElementById(f20obj); }
var f20txt=f20obj.value;
f20FormatNumber(f20obj,f20format,f20m,f20date);
f20obj.style.color=f20InitialColor;
f20obj.value=f20txt;
}

function f20FormatNumber(f20obj,f20format,f20m,f20date){
if (typeof(f20obj)=='string') f20obj=document.getElementById(f20obj);
var f20value=f20obj.value.replace(/D/g,''); ;
var f20valuecnt=0,f20fnu='';
if (f20obj.value.length>0){
for (var f200=0;f200<f20format.length;f200++){
f20fnu+=(f20format.charAt(f200)=='~')?f20value.charAt(f20valuecnt++):f20format.charAt(f200);
if (f20valuecnt>f20value.length) break;
}
}
f20obj.style.color=(f20fnu.length!=f20format.length)?f20TypingColor:f20CompleteColor;
f20obj.value=f20fnu;
f20SelRange(f20obj,f20fnu.length);
f20obj.date=f20date;
f20obj.format=f20format;
if (f20m){
if (f20m.toLowerCase().match('b')) f20AddEvt(f20obj,'f20Blur','blur');
if (f20m.toLowerCase().match('a')&&!f20obj.ckall){ f20obj.ckall=true; f20CkAllAry.push(f20obj); }
}
f20AddEvt(f20obj,'f20Color','focus');
}

function f20Blur(f20evt,f20obj){
f20obj=f20obj||this;
f20obj.style.color=f20CompleteColor;
if (f20obj.value.length<f20obj.format.length){
if (f20obj.value.length<1){ f20obj.value='Please Complete'; }
f20CkAllCk=false
f20Warning(f20obj,'Please Complete the');
}
if (f20obj.date&&window['f20DateTime']){ f20DateTime(f20obj); }
}

function f20CheckAll(){
f20CkAllCk=true;
for (f200=0;f200<f20CkAllAry.length;f200++){
f20Blur(null,f20CkAllAry[f200]);
}
return f20CkAllCk;
}

function f20Warning(f20obj,f20mess){
f20obj.style.color=f20WarningColor;
alert(f20mess+'nthe '+f20WarningColor+'nField');
f20War=true;
f20CkAllCk=false
f20obj.focus();
}

function f20Color(){
if (!f20War){ this.style.color=f20TypingColor; }
f20War=false;
}

function f20SelRange(f20obj,f20srtend) {
if (f20obj.setSelectionRange) {
f20obj.focus();
f20obj.setSelectionRange(f20srtend,f20srtend);
}
else if (f20obj.createTextRange) {
var range = f20obj.createTextRange();
range.collapse(true);
range.moveEnd('character',f20srtend);
range.moveStart('character',f20srtend);
range.select();
range.collapse(true);
}
}

function f20EventAdd(f20o,f20t,f20f) {
if ( f20o.addEventListener ){ f20o.addEventListener(f20t, function(e){ f20o[f20f](e);}, false); }
else if ( f20o.attachEvent ){ f20o.attachEvent('on'+f20t,function(e){ f20o[f20f](e); }); }
else {
var f20prev=f20o["on" + f20t];
if (f20prev){ f20o['on'+f20t]=function(e){ f20Prev(e); f20o[f20f](e); }; }
else { f20o['on'+f20t]=f20o[f20f]; }
}
}

function f20AddEvt(f20obj,f20fun,f20evt){
if (f20obj['f20add'+f20fun]) return;
f20obj['f20add'+f20fun]=window[f20fun];
f20EventAdd(f20obj,f20evt,'f20add'+f20fun);
}


// Following Code is required for date and time

function f20DateTime(f20){
var f20mess=[];
if (f20.date[0].charAt(0)=='d'||f20.date[0].charAt(0)=='m'){ f20mess=f20CkDate(f20); }
if (f20.date[0].charAt(0)=='t'){ f20mess=f20CkTime(f20); }
if (f20mess.length>1){ f20Warning(f20,f20mess.join('n')); }
}

function f20CkDate(f20obj){
var f20mess=['Please Correct the '+f20WarningColor+' Field Date'],f20s=f20obj.date[0].charAt(2),f20y=parseInt(f20obj.value.split(f20s)[2]);
if (f20obj.date[0].charAt(0)=='m'){
f20d=parseInt(f20obj.value.split(f20s)[1]);
f20m=parseInt(f20obj.value.split(f20s)[0]);
}
if (f20obj.date[0].charAt(0)=='d'){
f20d=parseInt(f20obj.value.split(f20s)[0]);
f20m=parseInt(f20obj.value.split(f20s)[1]);
}
f20md=new Date(f20y,f20m,1,-1).getDate();
if (!f20obj.date[1]){
f20obj.date[1]=f20MinYear;
f20obj.date[2]=f20MaxYear;
}
if (f20y<f20obj.date[1]||f20y>f20obj.date[2]) f20mess.push('Incorrect Year');
if (f20m<1||f20m>12) f20mess.push('Incorrect Month');
if (f20d<1||f20d>f20md) f20mess.push('Incorrect Day');
return f20mess;
}

function f20CkTime(f20obj){
var f20mess=['Please Correct the'+f20WarningColor+' Field Time'],f20a=0;
if (f20obj.value.match(f20obj.date[2])) f20a=12;
f20obj.value=f20obj.value.replace(f20obj.date[1],'');
f20obj.value=f20obj.value.replace(f20obj.date[2],'');
f20h=f20obj.value.substring(0,2)*1+f20a;
f20m=f20obj.value.substring(3,5);
if (f20h>23) f20mess.push('Incorrect Hours');
if (f20m>59) f20mess.push('Incorrect Minutes');
if (f20obj.date[1]&&f20obj.date[2]&&f20mess.length<1){
if (f20h<12) f20obj.value+=f20obj.date[1];
else f20obj.value=f20FormatNu(f20h-12)+(f20obj.value.charAt(2))+(f20FormatNu(f20m)+f20obj.date[2]||' PM');
}
return f20mess;
}

function f20FormatNu(f20nu){
return (f20nu<10)?'0'+f20nu:f20nu;
}

//-->
</script>
</head>

<body>
<input name="" size="15" value="Phone Number" style="color:gray;" onkeyup="f20FormatNumber(this,'~~ ~~ ~~ ~~ ~~','Blur');" ><br>

</body>

</html>[/CODE]
×

Success!

Help @A__Supertramp spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...