Validate emails fields in forms on the Fly

If you’re adding a knack form that includes an email input field, you may want to make sure that users enter a valid email address. You can add a simple email validator to your form using JavaScript.

The code uses regular expressions to check if the email input matches a pattern of a valid email address. It also adds visual feedback to the input field to show if the email is valid or invalid.

As the user types they will get live feedback based on the email typed from this…
image
to this… ⇩
image

To get started you must make sure that the email field type is present on the form you wish to collect the email from and then simply copy the below code snippets.

Javascript

$(document).on('knack-scene-render.any', function() {
  const emailInput = $('input[type="email"]');
  const emailValidatorText = $('<div class="emailValidaorText"></div>').hide();
  $('.kn-input-email label').append(emailValidatorText);
  // Active Email Input
  emailInput.on('blur', function() {
    validateEmail($(this));
  });
  // Keystroke
  emailInput.on('keyup', function() {
    validateEmail($(this));
  });
  function validateEmail(emailInput) {
    const email = emailInput.val().trim();
    const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    const emailInputHasValue = emailInput.val() !== '';
    // Adds or removes the classes 'validEmail' and 'invalidEmail'
    emailInput.closest('.kn-input-email')
      .toggleClass('validEmail', isValid)
      .toggleClass('invalidEmail', !isValid);
    // Updates the email validator text
    if (emailInputHasValue) {
      emailValidatorText.text(
        isValid ? '✅ Valid Email' : '❌ Invalid Email'
      ).slideDown(500);
    } else {
      emailValidatorText.slideUp(500);
    }
  }
});

CSS

.kn-input-email {
  transition: all .5 all;
}

.invalidEmail {
  border-radius:.5em;
  padding:5px;
}

.validEmail {
  border-radius:.5em;
  padding:5px;
}


.emailValidaorText {
    background: rgb(236, 235, 235);
    padding: 2px 7px;
    border-radius: 1em;
    position: absolute;
    top: 5px;
    right: 5px;
    font-weight: 250;
    color: rgb(26 25 25);
    margin-top: -10px;
}

Have fun and if you have any questions then please add a comment below

6 Likes

Thanks @Johnny_Appknowledged_UK - A great piece of code providing an elegant email format validation.
I especially love that it is simply a “copy & paste” process. Ideal for us no coders :+1:
Much appreciated.

1 Like

Thank you @Johnny_Appknowledged_UK this looks great. Really enjoying all your examples as we are getting a lot from them.

1 Like

You’re welcome @CSWinnall. Any more ideas would be appreciated

Brilliant @Johnny_Appknowledged_UK - thanks!

2 Likes

Thanks for the solution!!! Is there a chance we can adjust to check different fields? Can we name the fields so we can access them through this kind of code?