Welcome to Community Week 2025! Join us to learn, connect, and be recognized as we celebrate the spirit of Community and the power of AI. Get the details  

"Validation to allows numbers only. onChange scripts " on variable at Maitain item. is it possible to force allow only Number????

smd
Tera Contributor

I have a Requirement for "Validation to allows numbers only. onChange scripts " on variable at Maitain item. is it possible to force allow only Number????

3 REPLIES 3

vinothkumar
Tera Guru

Hi Dinesh,



Try something as similar,



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


    if (!isLoading) {


          if (newValue != '') {


                //get the integer value of the field


                var nbrwn = g_form.getIntValue('<your variable>');


                //check to see if there are any non numeric characters in the string


                if ((isNaN(newValue) == true) || (nbrwn < 0)) {


                      alert("This field should contain a whole number 0, 1, 2, 3, ... (and so on)");


                      g_form.setValue('<your variable>', '');




                }




          }


    }


}


Madhu27
Tera Expert

Please try the following on change script on 'new_field_value'



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


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


return;


}



//Type appropriate comment here, and begin script below


if(!isLoading){


var val = newValue;


var achar = '0123456789.';


var failmsg = 'Please enter only numeric values';



//create an array that is all lowercase based on the value if you want this case sensitive remove .toLowerCase()


var numeric_val = 'true';


var array1 = val.toLowerCase().split('');


for (var i=0; i < array1.length; i++){


if (achar.indexOf(array1[i]) >= '0'){


}


else{


numeric_val = 'false';


}


}



if (numeric_val == 'false'){


alert(failmsg);


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


}


}



}




Thanks


PS: Please hit Like/Helpful....if it helps


shivam_singhal
ServiceNow Employee
ServiceNow Employee

Hi Dinesh,



Refer to the below script, I have this one to address your use-case :



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


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


          return;


    }




    //Type appropriate comment here, and begin script below



var yn = g_form.getValue('yn');


if (yn === 'Yes') {


var value_one = g_form.getValue('one');


var value_two = g_form.getValue('two');


if (value_one && !isNaN(value_one))


g_form.setValue('one', value_one *= 2);



if (value_two && !isNaN(value_two))


g_form.setValue('two', value_two *= 2);



}


  }



This onChange catalog client script is increasing the value of 'one' and 'two' variables by twice if I have 'yn' as Yes.
so, before increasing the value to twice, I was checking for (Not-a-Number) isNaN(); in the above bold lines.



Don't forget to mark this the correct answer, if this solves your use-case.