Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Simple form validation

Validating a form in the browser tells the user about a mistake right away, without waiting for the server. The server must still check the data itself: browser code is easy to bypass. Validation with jQuery is a submit handler that looks at the field values and cancels submission on error.

One rule

<form id="signup">
  <input name="name" placeholder="Name">
  <button>Sign up</button>
  <p class="error"></p>
</form>
 
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
  $('#signup').on('submit', function (event) {
    event.preventDefault();
 
    const name = $(this).find('[name="name"]').val().trim();
 
    if (name === '') {
      $(this).find('.error').text('Enter your name');
      return;
    }
 
    $(this).find('.error').text('');
    console.log('Form submitted, name:', name);
  });
</script>

Press the button with an empty field: "Enter your name" appears below it. The string method trim() removes spaces at the edges, so a name of only spaces counts as empty too.

Several fields

For several fields it is handy to keep a message next to each field and collect errors in an object:

<style>
  .invalid { border-color: crimson; }
  .message { color: crimson; font-size: 13px; margin: 2px 0 8px; }
</style>
 
<form id="signup">
  <div><input name="name" placeholder="Name"><p class="message"></p></div>
  <div><input name="email" placeholder="Email"><p class="message"></p></div>
  <button>Sign up</button>
</form>
 
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
  function validate(values) {
    const errors = {};
    if (values.name.length < 2) errors.name = 'Name needs at least 2 characters';
    if (!values.email.includes('@')) errors.email = 'Use an email like anna@example.com';
    return errors;
  }
 
  $('#signup').on('submit', function (event) {
    event.preventDefault();
 
    const $form = $(this);
    const values = {
      name: $form.find('[name="name"]').val().trim(),
      email: $form.find('[name="email"]').val().trim(),
    };
    const errors = validate(values);
 
    $form.find('input').each(function () {
      const message = errors[this.name] || '';
      $(this).toggleClass('invalid', message !== '');
      $(this).next('.message').text(message);
    });
 
    if ($.isEmptyObject(errors)) {
      console.log('Sending:', $form.serialize());
    }
  });
</script>

The validate() function knows nothing about the page: it takes values and returns errors. The handler highlights wrong fields with the invalid class and writes the message into the next paragraph. $.isEmptyObject() checks that there are no errors.

Clearing an error on fix

<style>
  .invalid { border-color: crimson; }
</style>
 
<input name="name" class="invalid" placeholder="Name">
 
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
  $('input').on('input', function () {
    $(this).removeClass('invalid');
  });
</script>

Start typing and the red border disappears. In the form above, this handler can be attached with delegation: $('#signup').on('input', 'input', ...).

Built-in browser validation

The browser checks the required, type="email" and minlength attributes by itself and blocks submission. They are often enough, and jQuery is needed for custom rules and messages. To stop the browser from showing its own hints, add the novalidate attribute to the form.

Common mistake

Treating browser validation as enough. A user can turn off JavaScript, change the code in developer tools or send a request to the server directly, bypassing the form. jQuery validation is for convenience; only a second check on the server protects the data.

Thanks for reading!

Donate to the site — we work hard for you.