Restirct a catalog field to allow alphanumeric values and not special characters

KS13
Tera Contributor

Hi 

Hoping someone can guide me to write a simple onChange catalog client script.  

Have a requirement, where a catalog field should allow alpha-numerical values and not allow special characters EXCEPT 'dashes' and 'dots/periods'

For example:

Allow: Test-123.com OR Test.123-456.

Restrict: Test-123$%^&.com

 

If allowed, set value, if Restricted, then throw an error message. 

 

Thank you in advance

KS

 

1 ACCEPTED SOLUTION

Vishal Birajdar
Giga Sage

Hi @KS13 

 

Below is the script.

 

    var field_value = g_form.getValue('your_catalog_field'); // Replace 'your_catalog_field' with the actual field name.
    var regex = /^[a-zA-Z0-9.-]+$/; // Regular expression to allow alphanumeric, dashes, and dots.

    if (!regex.test(field_value)) {
        alert("Invalid input! Please use only alphanumeric characters, dashes, and dots.");
      
    }

   

 

You can also do this with Validation regex option for this.

 

VishalBirajdar_0-1696471900408.png

 

Vishal Birajdar
ServiceNow Developer

I know one thing, and that is that I know nothing.
- Socrates

View solution in original post

3 REPLIES 3

Vishal Birajdar
Giga Sage

Hi @KS13 

 

Below is the script.

 

    var field_value = g_form.getValue('your_catalog_field'); // Replace 'your_catalog_field' with the actual field name.
    var regex = /^[a-zA-Z0-9.-]+$/; // Regular expression to allow alphanumeric, dashes, and dots.

    if (!regex.test(field_value)) {
        alert("Invalid input! Please use only alphanumeric characters, dashes, and dots.");
      
    }

   

 

You can also do this with Validation regex option for this.

 

VishalBirajdar_0-1696471900408.png

 

Vishal Birajdar
ServiceNow Developer

I know one thing, and that is that I know nothing.
- Socrates

Amit Gujarathi
Giga Sage
Giga Sage

HI @KS13 ,
I trust you are doing great.
Here's a simple onChange catalog client script for your requirement:

 

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

    // Regular expression to allow alphanumeric, dashes, and dots/periods
    var regex = /^[A-Za-z0-9-.]+$/;

    if (!regex.test(newValue)) {
        // If the value does not match the regex, show an error message
        g_form.showFieldMsg(control, 'Special characters are not allowed except dashes and dots/periods.', 'error');
        g_form.clearValue(control); // Optionally, you can clear the field value
    } else {
        // If the value matches the regex, clear any previous error messages
        g_form.hideFieldMsg(control);
    }
}

 


Was this answer helpful?


Please consider marking it correct or helpful.


Your feedback helps us improve!


Thank you!


Regards,


Amit Gujrathi



Hi Amit, 

Thank you for the guidance. It works partially. It won't throw the error.