Too much recursion

Chris York
Tera Expert

I have a phone number field that I want formatted when someone types in just numbers. I wrote this onChange client script to handle the formatting. The script runs and does what it is supposed to, except that it also produces a javascript error of "too much recursion".

I have no idea why this error is happening. Can any javascript gurus out there help me?


Here is the script:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
//If the page isn't loading
if (!isLoading) {
//If the new value isn't blank
if(newValue != '') {
//Format the number
var newNumber = formatPhone(newValue);
g_form.setValue('u_contact_number', newNumber);
}
}
}

/**
* Format phone numbers
*/
function formatPhone(phonenum) {
var regexObj = /^(?:\+?1[-. ]?)?(?:\(?([0-9]{3})\)?[-. ]?)?([0-9]{3})[-. ]?([0-9]{4})$/;
if (regexObj.test(phonenum)) {
var parts = phonenum.match(regexObj);
var phone = "";
if (parts[1]) {
phone += parts[1] + "-";
}
phone += parts[2] + "-" + parts[3];
return phone;
}
else {
//invalid phone number
return phonenum;
}
}

3 REPLIES 3

CapaJC
ServiceNow Employee
ServiceNow Employee

Looks like only Firefox has a problem with that. IE9 and Chrome work just fine for me.

Before doing the setValue, you probably want to make sure your field doesn't already HAVE that value. That should avoid the recursion.


Chris York
Tera Expert

IE8 also has a problem. That's how I found it. I use Chrome and never saw the problem until a user pointed it out that was using IE8. I was able to replicate it using Firefox.


Chris York
Tera Expert

Good suggestion James, I added a check before the setValue and it works without error now

I still don't understand why, but at least it is resolved now.

var newNumber = formatPhone(newValue);
if (newNumber!=newValue){
g_form.setValue('u_contact_number', newNumber);
}