Regular expression to restrict 20 characters in single line text variable

Rajesh Mushke
Mega Sage
Mega Sage

HI All,

I need help to build regular expression to restrict enter 20 numbers & below characters in single line text.

20 Numeric and only the special characters that include: + ( ) - 

 

Thanks in advance.!

 

Thanks,

Rajashekhar Mushke



Thanks,
Rajashekhar Mushke
Rising star : 2022 - 2024
Community Leader -2018
Connect me on LinkedIn : Rajashekhar Mushke
17 REPLIES 17

Goran WitchDoc
ServiceNow Employee
ServiceNow Employee

Hi,

 

Try this: /^[\+\-()0-9]{1,20}/

I use sites like regex101.com. Here is a link to my specific regex: https://regex101.com/r/jHjOrA/1

//Göran
Feel free to connect with me:
LinkedIn & Twitter
Subscribe to my YouTube Channel
Buy The Witch Doctor's Guide To ServiceNow

Hi Goran,

 

Not working i can still able to enter text in the variable

 

Thanks,

Rajashekhar Mushke



Thanks,
Rajashekhar Mushke
Rising star : 2022 - 2024
Community Leader -2018
Connect me on LinkedIn : Rajashekhar Mushke

Service_RNow
Mega Sage

Here you go:

1) To limit 50 characters set max_length=50 in the attribute section for that catalog variable. so no need for regular expression for this.

 

max length catalog variable.JPG

 

2) Have onChange Catalog Client script to validate the values are number, dash, underscore etc. on that variable.

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

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

return;

}

var validate = new RegExp('^[a-zA-Z0-9-_]+$');

// a-zA-Z means letter

// 0-9 means allow numbers

// - and _ means allow this characters

// try giving value with length as less than 50 and special character such as @ or ! and it should throw the alert message and clear the variable

var result = validate.test(newValue);

if(!result)

{

// value is invalid show alert message and clear the variable

alert('Please give only letters, numbers, dashes, and underscores');

g_form.clearValue('<variableName>'); // add variable name here

}

}

Mark Correct if this solves your issue and also hit Like and Helpful if you find my response worthy based on the impact.

asifnoor
Kilo Patron

Hi, 

Try this regex and it should work

/^[0-9-+()]{1,20}$

Mark the comment as a correct answer and also helpful once worked.