Form validation made super easy with jQuery

We spend a lot of time coding both client and server-side form valdilation.

This is the routine I now always use for client-side validation, which has been refined over the years to become what I’d consider to be some pretty tight code, whilst providing good quality feedback to the user to help them complete forms quickly and with minimal confusion.

Hopefully you can learn a trick or two that you can use yourself, by looking at the code…

function errorBefore(error, $insertBefore) {
  $('<p class="error">' + error + '</p>').insertBefore($insertBefore);
}

$(function () {

  $("#my-form").submit(function (e) {

    // remove any errors from previous form submission
    $('.error', $(this)).remove();

    // get jQuery reference to form fields
    var $name = $('#name');
    var $email = $('#email');

    // validate name input
    if (!$name.val()) {
      errorBefore('Please enter your name.', $name);
    }

    // validate email input
    if (!$email.val()) {
      errorBefore('Please enter your email.', $email);
    }

    // check for errors
    if ($('.error', $(this)).length) {

      // find first error and focus on form field it relates to
      $('.error', $(this)).first().next('input, select, textarea').focus();

      // stop form submission
      e.preventDefault();
    }

  });

});

Leave a Reply