Issue with Regex

Praveen Mariapp
Tera Contributor

I am trying to do a regex validation in On change catalog client script to check that the start and end of a text variable value is either letters or numbers ONLY. No special characters allowed.

 

Below is the code I am using:

 

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

var field = "sample_text"; //sample_text is the name of the variable I created in the catalog item
var regex = /^[A-Za-z0-9]+ [A-Za-z0-9]+$/;

if (regex.test(g_form.getValue(field))) {
g_form.showFieldMsg(field, "Valid", "info");
} else {
g_form.showFieldMsg(field, "Invalid", "error");
}
}

 

It always says 'Invalid' even if I enter appropriate text (e.g., test) in to the field. Any help would be greatly appreciated.

1 ACCEPTED SOLUTION

Made below regex for your requirement, tested and covers all your conditions:

/^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$/

 

Please mark answer as Correct or Helpful based on impact.

By marking my response as correct or helpful, you contribute to helping future readers with similar issues.
Regards,
Abhijit
ServiceNow MVP

View solution in original post

4 REPLIES 4

Abhijit4
Mega Sage

Use below regex pattern instead:

/^[A-Za-z0-9]*$/

 

Updated script :

 

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

var field = "sample_text"; //sample_text is the name of the variable I created in the catalog item
var regex = /^[A-Za-z0-9]*$/;

if (regex.test(g_form.getValue(field))) {
g_form.showFieldMsg(field, "Valid", "info");
} else {
g_form.showFieldMsg(field, "Invalid", "error");
}
}

 

Please mark answer as Correct or Helpful based on impact.

 

By marking my response as correct or helpful, you contribute to helping future readers with similar issues.
Regards,
Abhijit
ServiceNow MVP

Hi Abhijit,

 

Thanks for the response. May be, I have to mention the complete requirement to make it straight forward:

 

Can contain letters or numbers and not case-sensitive

No special characters are allowed except hyphen

Should not start or end with a hyphen

Can not have multiple consecutive hyphens

 

Achieving all of this in a single Regex was beyond my knowledge at the moment. So, I was trying to split and achieve with multiple statements. Anyway, above is the complete requirement.

Made below regex for your requirement, tested and covers all your conditions:

/^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$/

 

Please mark answer as Correct or Helpful based on impact.

By marking my response as correct or helpful, you contribute to helping future readers with similar issues.
Regards,
Abhijit
ServiceNow MVP

works like a charm, many thanks Abhijit