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…
to this… ⇩
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