logo

NJP

Field validation: Regular Expressions

Import · Sep 20, 2020 · article

Sometimes we want to help the user by validating if the input is correct/what we expect in the system. For example if the user inputs a phone number, url or email address.

Regular expression

Wikipedia: A regular expression (shortened as regex or regexp; also referred to as rational expression) is a sequence of characters that define a search pattern.

Basically we provide the system a pattern it can use to search any string value with and allow it to do some action when a match is found.

Using regular expression: Variable Validation Regex

You can use regular expressions throughout the system. If you want to validate a value input in the Service Catalog for a user requesting an item you can set up a Variable Validation Regex:

image

Existing Regular expressions

There are already a few Regular expressions available in the system:

image

Add a new one

You can add your own Regular expression to this. For example if we want to check if an email address that is entered is valid:

image

Apply it to a Variable

To apply it to a Question/Variable, go to the variable and select the regular expression you like to use in the Type Specification:

image

The result

A valid email address format:

image

Invalid format:

image

Reference the Docs article here: https://docs.servicenow.com/bundle/orlando-it-service-management/page/product/service-catalog-manage...

Using regular expression: onChange client script

We can get the same result using an onChange client script. With the added benefit that we can use an onChange script in a Catalog Client script, as well as on a form in the back-end.

To do this add the following code to an onChange client script on the field you want to validate:

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var re = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;
    if (!re.test(newValue)) {
        g_form.showFieldMsg('your_field name', 'Please enter a valid email address', 'error');
        return false;
    }
    return true;
}

Like so:

image

Common Regular expressions

For common Regular expressions, please refer to this article:

https://community.servicenow.com/community?id=community_article&sys_id=453fa36edbd7d0103daa1ea668961...

View original source

https://www.servicenow.com/community/developer-articles/field-validation-regular-expressions/ta-p/2321095