How to Disable the Space Key Inside a Form Field


Would you like to disable the space key inside your WPForms fields? You can easily do this by adding a CSS class name to your form field and a small JavaScript snippet. In this tutorial, we’ll walk you through each step on how to disable the space key in your form fields.

Creating the form

First, we’ll start by creating a new form. For the purpose of this tutorial, we’re going to be creating a user registration form in which our visitors can set their own usernames. Since this will be what they use to log into our site, we don’t want to allow any spaces in this field.

We’ll start by adding a Single Line Text form field. Once added, we’re going to add a specific class name that we’ll use in our snippet to trigger the script to run.

Just add the wpf-disable-space to the CSS Classes field on the Advanced tab.

Just add the CSS class of wpf-disable-space to the  CSS Classes field on the Advanced tab.

For assistance on how to create a form with WPForms, please check out this documentation.

Adding the snippet

Now it’s time to add the snippet to our site.

If you need any assistance on how and where to add snippets to your site, please check out this tutorial.

 * Disable the space key with the special CSS class
 * Apply the class "wpf-disable-space" to the field to enable.
 * @link
function wpf_dev_disalbe_space() {
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            jQuery( '.wpf-disable-space input' ).keydown(function(e) {
				if (event.key === ' ') {
					return false;
add_action( 'wpforms_wp_footer_end', 'wpf_dev_disalbe_space', 10 );

The event.key in the snippet followed by the three equals sign represents a specific keyboard key pressed. For the space bar, the key is just an empty space.

If you’d like a complete list of other special numerical representations, please check out this article.

Now when the user tries to enter the Username field of our form, they will not be able to enter a space for the Username.

All you need to do for all future forms is only add the special CSS class name to the CSS Classes field in the Advanced tab of the field while inside the form builder.

And that’s it! You’ve successfully disabled the space key inside your form field! Would you like to prevent any special characters inside a form field? Check out our tutorial on How to Restrict Special Characters From a Form Field.

Action Reference: wpforms_wp_footer_end