Is there a way to ensure that special characters are not entered in a single line text field

Cupcake
Mega Guru

I have a variable that is a single line text field. The customer wants to ensure that these conditions are met. Is there a way to accomplish this?

Must NOT contain the following printable characters: / : \ ~ & % ; @ ' " ? < > | # $ * } { , + = [ ].
Must NOT start with an underscore (_).

 

Thanks,

Karen

1 ACCEPTED SOLUTION

Here's one that does both AND wipes the field:

 

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

var nospec = g_form.getValue('nospecial');
var ucheck = nospec.startsWith("_");
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
if (pattern.test(nospec)){
	alert("No special characters!");
	g_form.setValue('nospecial', '');
	return false;
}

	if (ucheck){
		alert("Cannot start with an underscore");
			g_form.setValue('nospecial', '');
		return false;
	}
	
	
	return true;

   
}

View solution in original post

9 REPLIES 9

Here's one that does both AND wipes the field:

 

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

var nospec = g_form.getValue('nospecial');
var ucheck = nospec.startsWith("_");
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
if (pattern.test(nospec)){
	alert("No special characters!");
	g_form.setValue('nospecial', '');
	return false;
}

	if (ucheck){
		alert("Cannot start with an underscore");
			g_form.setValue('nospecial', '');
		return false;
	}
	
	
	return true;

   
}

Because "newValue" already contains the new value of the string field, you can skip the "var nospec = g_form.getValue("nospecial");" line and replace "nospec" with "newValue" in the 2 places it's used.

Or, at least, replace the g_form.getValue line with:

nospec = newValue;

A little tweak to improve performance as much as possible.

Thanks Shane. This worked perfectly.

A lot more clearer now that you've explained it.

 

Much appreciated and Happy Holidays to you and your family.

Karen

Same to you Karen, glad I could help.  😃

agopalrao
Mega Contributor

You can try this to avoid entering the keys while typing. I haven't verified it in all the browsers. So this need more testing in all browsers.

function onLoad() {
//Type appropriate comment here, and begin script below

       g_form.getElement('element_name').onkeypress=function(event) {
               var charArray = [47,58,92]; //Placed some sample key codes / : \
                if(charArray.includes(event.keyCode)) {
                      return false;
                }

//write your first character condition code here. or build some other logic....
                return true;
       }
}