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.
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.
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