How to Restrict Start and End Spaces in string

rambabu1
Giga Expert

Hi,

Using below script unable to restrict spaces in start and end of string. it's working only if the space in middle of the string.

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

var regx = new RegExp("^[a-zA-Z0-9_-]*$");

if (!regx.test(newValue)) {

alert('No Special Chars are allowed except "_" and "-"');
g_form.setValue('name', '');
}
}

2 REPLIES 2

Allen Andreas
Administrator
Administrator

Hello,

You can use this as an example of regex: https://stackoverflow.com/questions/34974942/regex-for-no-whitespace-at-the-beginning-and-end#:~:tex...

And then make any further adjustments needed to allow your special characters.

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

Hi Allen,

below script not working in service portal. unable to remove the space at starting and ending

please see the screenshot as well

find_real_file.png


var regx = /^[A-Za-z0-9_-\s]*$/;
var res = g_form.getValue('name');
var name = res.replace(' ', '');


if (!regx.test(newValue)) {

alert('No Special Chars are allowed except "_" and "-"');
g_form.setValue('name', '');

} else {

g_form.setValue('name', name);

}

}