How to validate a string field for proper phone number format

quanha
Kilo Contributor

I have a need to validate a string field in a record producer for proper phone number formatting (xxx) xxx-xxxx. I understand that a client script for onSubmit should cover it, but I can't seem to devise a proper script that does the validation. Does anyone have a sample validation script that is working for them?

10 REPLIES 10

sebastian_g_snc
ServiceNow Employee
ServiceNow Employee

Late reply - nevertheless:
There are phone number fields (starting in Dublin) - maybe that helps:


Using Phone Number Fields - ServiceNow Wiki


We recently upgraded to Eureka and the phone number field type works out perfectly.


randrews
Tera Guru

what type of phone number?? US international both... it complicates things a LOT if not dealing with just one country



this is the standard function/format i use for a regex test... just look up a regex that tests for phone numbers that you like and plug it in the regex variable, and put your field and message in the err_field and err_message




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



if (!isLoading){


    var err_field = 'u_gl_period';


    var err_message = 'GL Period must be at formatted as mm-yyyy',


  regex = /^(0[1-9]|1[012])\-(19|20)\d{2}$/;


    var err_flag = 'false';


    err_flag = regex.test(g_form.getValue(err_field));


    g_form.hideErrorBox(err_field);


    if (!err_flag){


g_form.showFieldMsg(err_field,err_message,'error');


            g_form.clearValue(err_field);


    }


    else{g_form.hideErrorBox(err_field);}


}


}


geoffcox
Giga Guru

Wouldn't it be better to change the format typed in to the desired format? This is what most contact software does.


This could be done in an onchange client script. The script should get rid of everything except the numbers, then re-format properly. Then it should compare the new string to the previous one (don't update the field if it hasn't changed) prior to updating the field. Without that test you could get stuck in an update loop.



Let me know if you need coding help on that solution.