Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

how to restrict special characters without restricting spaces in string field

kalyani23
Tera Contributor

Hi, i want to restrict special characters in string field. And I used the below script , it is restricting spaces also, can anyone help on how to achieve this, without restricting spaces.

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

//Type appropriate comment here, and begin script below.

var regex = new RegExp("^[a-zA-Z0-9]*$"); //no special characters
var str = g_form.getValue('title_of_the_usecase');
var len = str.length;

if(!regex.test(newValue))

{
alert('Please enter only letters');
g_form.setValue('title_of_the_usecase','');
}

}

Regards,

kalyani

1 ACCEPTED SOLUTION

Hitoshi Ozawa
Giga Sage
Giga Sage

Complete script.

function onChange(control, oldValue, newValue, isLoading) {
    if (newValue != '') {
        var regex = /^[a-zA-Z0-9\s]*$/;
        if (!regex.test(newValue)) {
            g_form.clearValue('title_of_the_usecase');
            g_form.showFieldMsg('title_of_the_usecase', "Please only enter letters.", "error");
		}
    }
}

Execution results:

case 1: OK

find_real_file.png

case 2: Special character. Entered "This has a special character $ in the sentence"

find_real_file.png

View solution in original post

4 REPLIES 4

Hitoshi Ozawa
Giga Sage
Giga Sage

Hi kalyani,

Use "\s"

var regex = new RegExp("^[a-zA-Z0-9\s]*$"); //no special characters

Musab Rasheed
Tera Sage

Hi Kalyani,

Use this

 /^[0-9a-zA-Z]*$/;

Regards

Please hit like and mark my response as correct if that helps
Regards,
Musab

Hitoshi Ozawa
Giga Sage
Giga Sage

Complete script.

function onChange(control, oldValue, newValue, isLoading) {
    if (newValue != '') {
        var regex = /^[a-zA-Z0-9\s]*$/;
        if (!regex.test(newValue)) {
            g_form.clearValue('title_of_the_usecase');
            g_form.showFieldMsg('title_of_the_usecase', "Please only enter letters.", "error");
		}
    }
}

Execution results:

case 1: OK

find_real_file.png

case 2: Special character. Entered "This has a special character $ in the sentence"

find_real_file.png

Thank you