Would you like to prevent users from entering spaces in certain form fields? This can be useful for usernames, email addresses, or other fields where spaces might cause issues.
This guide will show you how to disable the space key in specific form fields using a CSS class and simple JavaScript.
Understanding the Need
When creating forms that require specific input formats, like usernames or codes, preventing spaces can help maintain data integrity. For example, in a user registration form, you might want usernames without spaces to ensure consistent login credentials.
Setting Up Your Form
First, create your form and add the fields where you want to disable the space key. If you need help creating a form, please see our guide on creating your first 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.
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.
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.
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! Next, 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.