phone number validations which is 8 digits character's limit ,it will allow only numbers (will not allow other charters like Special symbols @,\$,A..)

padhu1
Kilo Expert

Hi Friends,

                                  phone number validations which is 8 digits character's limit ,it will allow only numbers (will not allow other charters like Special symbols @,$,A..) .can any one give me sample code.

Thanks in Advance.

14 REPLIES 14

veena_kvkk88
Mega Guru

Hi,



You can use an onChange and an onSubmit client script to validate a field (you need both because even if we put out an alert in the onChange, user can still save the form)



Here's a sample for the onChange on the phone number field. This is pretty basic, allows only 8digits. If you need other validations like checking if it starts with 0 or allowing hyphens or brackets like we usually have in phone number formats, the regex needs to be tweaked.



function onChange(control, oldValue, newValue, isLoading, isTemplate) {


    if (isLoading || newValue === '') {


          return;


    }


    g_form.hideFieldMsg('u_field_name');


    var regex = /^[0-9]*$/;


    if(!regex.test(newValue) || newValue.length != 8){


      alert('Invalid value. Please enter only 8 digit phone number.');


    }


}



onSubmit would be similar to this, except you replace newValue with g_form.getValue('u_field_name').


The regex should be /^[0-9]{8}$/ if only 8 digits are permitted (and no spaces, brackets, etc).


Yes Dave, that looks simpler! My code is checking for length too but not in the regex. Thanks for the update!


twright5
Kilo Expert

I did this quick at Knowledge 17 so let me know if you have any issues:



function onChange(control, oldValue, newValue, isLoading, isTemplate) {


    if (isLoading || newValue === '') {


          return;


    }


    g_form.hideFieldMsg('u_field_name');
    var regExp = /^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}/;
 
    if(!regExp .test(newValue) || newValue.length != 10){


      alert('Invalid value. Please enter only 10 digit phone number. ex: (314) 555-5555 ');


    }
    else
    {
    var maskedNum = newValue.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
    g_form.setValue('u_phone_number', '(' + maskedNum[1]   + ') ' + maskedNum[2] + '-' + maskedNum[3])
 
    }


}


Chandra Rawat
Kilo Contributor

Hi Padhu,



Please use this on change Client script and mark it as helpful.



function onChange(control, oldValue, newValue, isLoading) {


  if (isLoading || newValue == '')


  {


  return;


  }



  if(newValue.match(/[!" £$%&*{}_=;:'@#~?.>,<|\^ ¬`]/) || newValue.indexOf("[") != -1 || newValue.indexOf("]") != -1 || newValue.match(/\\/g) || newValue.match(/[a-zA-Z][a-zA-Z ][a-z]/) || newValue.match(/^[a-z]/))


  {



  alert('Please enter a valid phone number.');


  g_form.setValue('phone_no', '');



  }




}