How to prevent special characters on a field

Jen11
Tera Expert

I have the following onChange client script to prevent spaces and maximum 15 characters on a string field.

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
var str = g_form.getValue('u_equipment_id_right_fax');
var regEx = /^\S{1,15}$/;
var valid = regEx.test(str);
if(!valid)
alert('Entered value has either spaces or length > 15');
}

 

To the script above I would like to add to prevent special characters to the field.

Could someone please help me where I can add that.

Thanks,

 

1 ACCEPTED SOLUTION

Raghu Loganatha
Kilo Guru

Hi, 

Try this. 

if (isLoading || newValue == '') {
return;
}
var str = g_form.getValue('u_equipment_id_right_fax'); 
var regEx = /^\S{1,15}$/;
var valid = regEx.test(str);
if(!valid)
alert('Entered value has either spaces or length > 15');

var specialCharRegex = /[~@|$^<>\*+=;?`')[\]]/;


if(specialCharRegex.test(valid)){

alert("no special characters allowed");

}
}

let me know if you have any questions or please mark as answered 

View solution in original post

4 REPLIES 4

Raghu Loganatha
Kilo Guru

Hi, 

Try this. 

if (isLoading || newValue == '') {
return;
}
var str = g_form.getValue('u_equipment_id_right_fax'); 
var regEx = /^\S{1,15}$/;
var valid = regEx.test(str);
if(!valid)
alert('Entered value has either spaces or length > 15');

var specialCharRegex = /[~@|$^<>\*+=;?`')[\]]/;


if(specialCharRegex.test(valid)){

alert("no special characters allowed");

}
}

let me know if you have any questions or please mark as answered 

Priyanka Gupta
Mega Guru

Hi Jen,

This should be your RegEx-

^\S{1,15}[^~`!@#$%^&()_={}[\]:;,.<>+\/?-]*$

You can re-write your code as-

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
var str = g_form.getValue('u_equipment_id_right_fax'); 
var regEx = /^\S{1,15}[^~`!@#$%^&()_={}[\]:;,.<>+\/?-]*$/;
var valid = regEx.test(str);
if(!valid)
alert('Entered value has either spaces or length > 15');
}

I would suggest using an online RegEx editor to test out regex patterns and strings like https://regex101.com/

Hit help/mark my answer correct if this is what you were looking for.

Priyanka

I tried to add the asterisk sign to the above, but it's not working: 

 

var regEx = /^\S{1,15}[^~`!@#$%^&*()_={}[\]:;,.<>+\/?-]*$/;

I have a use case, whether we should allow any specia characters in a string field. what RegEx should be used for this scenario? Could you please help?