Link to home
Start Free TrialLog in
Avatar of Jack Andrews
Jack AndrewsFlag for United States of America

asked on

How to prevent users from entering a series of consecutive spaces in a form field

Occasionally, a user will enter spaces in our HTML5 validated form to avoid entering a name, such as a competitor checking out the form. How do we use html5 validation to require at least 3 characters and/or not more than one space? I am not a coder, but I think it is something like
input:invalid [ | ] for disallowing two consecutive spaces, but that's all I know.
Avatar of zephyr_hex (Megan)
zephyr_hex (Megan)
Flag of United States of America image

Here's one way to do it:

https://jsfiddle.net/zephyr_hex/z4p42krx/

HTML
<input type="text" id="name" placeholder="name"><span></span>

Open in new window


jQuery
$(document).ready(function() {
  $('#name').on('blur', function(e) {
    var name = $(this).val();
    if (name.indexOf("  ") >= 0) {
      $(this).next('span').text('double spaces are not allowed');
    }
  });
  $('#name').on('focus', function() {
    $(this).next('span').text('');
  });
});

Open in new window

Avatar of Jack Andrews

ASKER

Thank you, Megan. I was hoping for a php solution, or one that would require an alphabetical entry. People who would do that are doing it intentionally anyway, in most cases, so their info should probably just be discarded on the receiving end.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.