We've updated the ServiceNow Community Code of Conduct, adding guidelines around AI usage, professionalism, and content violations. Read more

how to restrict special characters without restricting spaces in string field

kalp
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

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

Hi kalyani,

Use "\s"

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

Musab Rasheed
Kilo Patron

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

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