Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Prevent characters in string fields

Giusy
Tera Contributor

Hi,

 

Does anyone know if it's possible to prevent operators from inserting certain characters in some string fields.
For example, I'd like to prevent the use of commas (,) and double quotes (") in the Resolution note field.
Can anyone help me?

 

Tks

3 REPLIES 3

Ankur Bawiskar
Tera Patron
Tera Patron

@Giusy 

there is no OOTB way to handle this

you can write custom client script which triggers onChange of that field and does that validation

something like this but please enhance

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    // Check if new value contains disallowed characters "," or """
    if (newValue.indexOf(',') !== -1 || newValue.indexOf('"') !== -1) {
        // Alert user
        alert('Commas (,) and double quotes (") are not allowed in this field.');

        // Revert the field value to the previous valid value
        g_form.clearValue('close_notes');
    }
}

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@Giusy 

Hope you are doing good.

Did my reply answer your question?

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

I tried this script but can't get it to work. After several tests, I decided to opt for a business rule on inserts and updates that removes the comma and double quotes from the field.

 

(function executeRule(current, previous /*null when async*/) {

    // Esempio: rimuovere tutti i caratteri non alfanumerici da un campo
    var valoreOriginale = current.close_notes + ''; // forza conversione a stringa
    var valorePulito = valoreOriginale.replace(/[",]/g, ''); // rimuove , e "
   
    // Aggiorna il campo solo se è cambiato
    if (valoreOriginale !== valorePulito) {
        current.close_notes = valorePulito;
        // Poiché è una Business Rule "after", serve un update esplicito
        current.update();
    }

})(current, previous);