How to Disable the Space Key Inside a Form Field

Introduction

Do you want to disable the space key in certain WPForms fields? Whether it’s to ensure data integrity or to enforce a specific input format, you can easily achieve this by adding a CSS class to your form field and a simple JavaScript snippet. In this tutorial, we will guide you through the process step-by-step, showing you how to disable the space key for specific fields in your form. By the end, you’ll be able to control which fields restrict space bar input, enhancing the functionality and accuracy of your form submissions.

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.

Disabling the space key

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 https://wpforms.com/developers/how-to-disable-the-space-key-inside-a-form-field/
 *
 */
  
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;
				}
				
			});
			
    });
    </script>
    <?php
}
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.

Reference Action

wpforms_wp_footer_end