1. test is NOT a variable
In ServiceNow client scripts, form fields cannot be accessed directly by their name. You must use g_form.getValue() to retrieve a field’s value.
if (test == '')
This condition will always fail because test is undefined.
2. You are exiting the function when the field is empty
This condition causes the script to return immediately:
if (isLoading || newValue === '') {
return;
}
So your validation logic never runs when the field is cleared.
If the onChange client script is on the test field itself
Option 1: Show alert when the user clears the field (most common use case)
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading) {
return;
}
if (newValue === '') {
alert('Test cannot be empty!');
}
}
If the onChange client script is on another field, but you want to validate test
Option 2: Check the test field value when a different field changes
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading) {
return;
}
var testValue = g_form.getValue('test');
if (!testValue) {
alert('Test cannot be empty!');
}
}