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

Brad Tilton
ServiceNow Employee
ServiceNow Employee

Hi Quan,



Here's a fairly lightweight script that we use onChange on variables pretty frequently. It allows for a few different phone number formats and uses a standard popup.



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


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


          return;


  }


  // Allows formats of (999) 999-9999, 999-999-9999, and 9999999999


  var pattern = /^[(]?(\d{3})[)]?[-|\s]?(\d{3})[-|\s]?(\d{4})$/;


  if(!pattern.test(newValue)){


          alert('Phone enter a valid phone number');


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


  }


}


This actually worked for us. Thanks!!


This worked for me as well. Thanks

Hi Brad,

 

I'm new to Regex. In the above solution is there a way to just allow the 999-999-9999 format? 

Also, are you able to explain the final line g_form.setValue('variablename', '')?  What exactly is that doing?

 

Thanks!

 

Justin

Daniel Pettet
ServiceNow Employee
ServiceNow Employee

Phone number formats are all about usability. So theoretically you should examine the number for appropriate formatting. Eg. 01834289969 could be 0183 428 9969 or 018 342 899 69 or (0) 1834 289969



So your formula needs to look for patterns in the numbers and speech easiness. I always prefer to have the number 69 on it's own because it's easier for most people to remember.*



* Obviously I'm not serious but you can imagine that there is not always a right way to format a number. Australian numbers are reasonably standard but German numbers have multiple formats and don't have fixed length numbers.



If you want a simple solution, just enforce a space every 3 and 4 digits for readability. Eg


018 3428 9969


(ensuring no groups of digits are less than 3)


OR


0183 428 9969 (better spacing for phone numbers with 11 digits)