Bagzli Bagzli - 1 year ago 58
Javascript Question

Trigger validation after first submit, then after after every keystroke on input element

I am using jquery validation for everything I'm about to talk below.

so I have an input field, lets call it email. I also have a submit button for this form. Now by default the error message for email field will not kick in until I hit the submit button. Then whenever I type it will show/hide error message dependant on if it is a valid email. This check happens with every key stroke and this is a very important distinction to make so that you would understand my problem I posted below.

Now I have a background colour on the input, it is suppose to be green when validation has passed and red when it has failed. I have this part working, let me show you how I did it:

window.onload = function () {
$(".js-validate-circle").on("input", function () {
function UpdateValidationCircle(e) {
if ($(e).valid()) {
} else {

class is what determines if its green or red. There is styling that is irrelevant I think to the question so I wont post it here.

Here is my problem: When the page loads and I start typing, it forces validation to trigger and error messages start coming in before I click the submit button for the first time. I am trying to prevent this. I want the color the start changing on typing only after the submit button was hit. Functionality of my red/green background should match jquery validation messages.

How would I accomplish something like this? I tried using on change but then the validation triggers only when the box loses focus.

Answer Source
jQuery(function($) { // DOM ready and $ alias in scope

// Cache elements
var $circle = $(".js-validate-circle");
var addedInputEvent = false; // Just a flag to know if we already added the evt listener

// On form submit....
$("#form").on("submit", function(event) {

   // Prevent default form submit

   // Check immediately

   // If not already assigned, assign an "input" listener
   if(!addedInputEvent) {
       addedInputEvent = true;
       $circle.on("input",  UpdateValidationCircle);

function UpdateValidationCircle() {
  var $el = $(this);
  $el.parent().toggleClass("active", $el.valid());