How to Restrict Special Characters From a Form Field

Overview

Would you like to restrict certain special characters from a form field? In some cases, there may be certain characters you want to disallow in a Single Line Text field. In this tutorial, we’ll show you how to restrict those characters using Javascript.

Setup

In our example below, we’re going to disallow the @ symbol and display an alert message if it’s typed into the text field.

1) Adding the JavaScript

First, you’ll need to copy the code shown below to your site.

/**
 * Restrict special characters from text field
 * Apply the class "wpf-char-restrict" to the field to enable.
 *
 * @link https://wpforms.com/developers/how-to-restrict-special-characters-from-a-form-field/
 *
 */
 
function wpf_dev_char_restrict() {
	?>
	<script type="text/javascript">
		jQuery(function($){
			$('.wpf-char-restrict input').on('keypress', function(event){
			  var regex = new RegExp("@");
    		  var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
				if (regex.test(key)) {
				   alert ("Please fill out the form in English. Thank you!"); // Put any message here
				   event.preventDefault();
				   return false;
				}
			}); 
		});
	</script>
	<?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_char_restrict' );

2) Adding the CSS Class

Next, you’ll need to open the form builder, click the field to open its Field Options panel and open the Advanced Options section.

Next, add wpf-char-restrict to the CSS Classes field.

restrict special characters with the javascript code above and adding the css class

And now if the user tries to type in the @ sign, they’ll see an alert message pop up on their screen.

Would you like to also use JavaScript to allow multiple dates to be selected from a date picker? If so, please check out our tutorial on How to Allow Date Range or Multiple Dates in Date Picker.

FAQ

Q: Can I also use this for other fields?

A: Absolutely. Here’s an example of that code snippet that will target all forms and all inputs that accept text.

/**
 * Restrict characters allowed to be entered into form
 */
function wpf_dev_restrict_characters() {
	?>
	<script type="text/javascript">
		jQuery(".wpforms-field-container input").on("keypress", function(event) {
		    var englishAlphabetAndWhiteSpace = /[A-Za-z0-9 ._^%$#!~@,-]/g;
		    var key = String.fromCharCode(event.which);
		    if (englishAlphabetAndWhiteSpace.test(key)) {
		        return true;
		    }
		    alert ("Please fill out the form in English. Thank you!"); // Put any message here
		});
	</script>
	<?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_restrict_characters' );