Results 1 to 3 of 3

Thread: phone number formatting in input

  1. #1
    Join Date
    Jan 2014

    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 this function 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?


  2. #2
    Join Date
    Oct 2010
    Versailles, France
    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)
    <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 ');
    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.
    Last edited by 007Julien; 01-27-2014 at 10:53 AM.

  3. #3
    Join Date
    Jun 2004
    Portsmouth UK
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    <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;
    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++){
       if (f20valuecnt>f20value.length) break;
     if (f20m){
      if (f20m.toLowerCase().match('b')) f20AddEvt(f20obj,'f20Blur','blur');
      if (f20m.toLowerCase().match('a')&&!f20obj.ckall){ f20obj.ckall=true; f20CkAllAry.push(f20obj); }
    function f20Blur(f20evt,f20obj){
     if (f20obj.value.length<f20obj.format.length){
      if (f20obj.value.length<1){ f20obj.value='Please Complete'; }
      f20Warning(f20obj,'Please Complete the');
     if (f20obj.date&&window['f20DateTime']){ f20DateTime(f20obj); }
    function f20CheckAll(){
     for (f200=0;f200<f20CkAllAry.length;f200++){
     return f20CkAllCk;
    function f20Warning(f20obj,f20mess){
     alert(f20mess+'\nthe '+f20WarningColor+'\nField');
    function f20Color(){
     if (!f20War){ this.style.color=f20TypingColor; }
    function f20SelRange(f20obj,f20srtend) {
     if (f20obj.setSelectionRange) {
     else if (f20obj.createTextRange) {
      var range = f20obj.createTextRange();
    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;
    // 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'){
     if (f20obj.date[0].charAt(0)=='d'){
     f20md=new Date(f20y,f20m,1,-1).getDate();
     if (!f20obj.date[1]){
     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;
     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;
    <input name="" size="15" value="Phone Number" style="color:gray;" onkeyup="f20FormatNumber(this,'~~ ~~ ~~ ~~ ~~','Blur');" ><br>

    God loves you and will never love you less.

    If my post has been useful please donate to http://www.operationsmile.org.uk/

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center

Recent Articles