Yuriy Zubarev
Yuriy Zubarev

Reputation: 2871

How to prevent validation method firing on every keystroke after the initial validation failure?

I have a form with the "name" input field, and it should be unique for the whole application. The check happens via Ajax call when a user tries to save the form. If user leaves the "name" empty and then saves the form, it will be followed by a validation error. After this point, every keystroke for the "name" field will be resulted in Ajax call. How to prevent this?

HTML:

<input type="text" name="name" value="${Name}" />

JS:

var validationParams = {
  rules: {
    name: {
      required: true,
      uniqueName: true
    }
  }
};

...

$.validator.addMethod("uniqueName", uniqueNameFn, 'error msg');

...

saveBtn.on('click', save);

...

function save() {
  templateRegion.find(form).validate(validationParams);
  if (!templateRegion.find(form).valid()) return;

  $.ajax({ ... });
}

// FIRES ON EVERY KEYSTROKE IF 'required' VALIDATION INITIALLY FAILS
function uniqueNameFn(value, elemChanged) {
  $.ajax({ ... });
}

Upvotes: 1

Views: 446

Answers (2)

Yuriy Zubarev
Yuriy Zubarev

Reputation: 2871

At the end of the day it wasn't jQuery or JavaScript problem. It was a nested forms situation.

Upvotes: 0

politus
politus

Reputation: 6086

set onkeyup to false in your validationParams object

var validationParams = {
    onkeyup:false,
    rules: {
        name: {
            required: true,
            uniqueName: true
        }
    }
};

Upvotes: 1

Related Questions