logo

NJP

Field validation: Does not contain

Import · Jan 21, 2021 · article

This is an addition to the Field validation: Regular Expressions article.

Where before we checked for a specific format and matched the pattern, this article allows us to check if the input does not contain a certain character or pattern.

A little recap

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.

For more info read Field validation: Regular Expressions article.

Negating

Negating is used if you want to check if the input does not contain a certain character or pattern.

For example:

[^a-zA-Z\d\s:]
  • a-zA-Z matches upper and lower case letters
  • \d matches digits
  • \s matches white space
  • : matches a colon The '[' at the start negates them all so you get non numeric characters (non letters and non digits), non spaces and non colons.

An example for this is to not allow special characters:

^[^$-/:-?{-~!"^_`\[\]]*$

image

Result

Valid inputs:

Letters [valid]:

image

Letters, numbers and space [valid]:

image

Special character [invalid]:

image

Prevent repetition

If you want to allow a value (for example special characters) but not multiple times, that can be done as well by using the following:

?=.\[-!$%&*()_+|~=`{}\[\]:";'<>?,.\/]*)(?!.*([-!$%&*()_+|~=`{}\[\]:";'<>?,.\/]).*\1).*$

  • abc$ - Starts/end with
  • <(?= - positive lookahead: Matches a group after the main expression without including it in the result.
  • .* - any character except newline 0 or more times
  • [-!$%&*()_+|~=`{}\[\]:";'<>?,.\/] - special characters
  • * - 0 or more times
  • ?! - negative lookahead: Specifies a group that can not match after the main expression (if it matches, the result is discarded).

Result

No special character [valid]:

image

1 or more special characters without repetition [valid]:

image

1 or more special characters repeated [invalid]:

image

Let me know if you have any additional use-cases for this and feel free to comment on any improvements! image

View original source

https://www.servicenow.com/community/developer-articles/field-validation-does-not-contain/ta-p/2309944