Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery "remote" validation
window.Em = window.Em || {};
Em = {
setFocusOutValidation: function (form) {
var s = $.data(form, "validator").settings;
s.onfocusout = function (element) {
if ($(element).val().length > 0) {
$(element).valid();
}
};
s.showErrors = function (map, list) {
this.defaultShowErrors();
if (list && list.length > 0) {
for (prop in map) {
$("#" + prop).focus();
}
}
Em.displayValidationSummaryErrors(list);
};
return s;
},
displayValidationSummaryErrors: function (list) {
$("[data-valmsg-summary]").removeClass("validation-summary-valid").addClass("validation-summary-errors");
$("[data-valmsg-summary] ul").html("");
$.each(list, function (idx, data) {
$("[data-valmsg-summary] ul").append($("<li></li>").html(data.message));
});
}
}
// The "remote" validation is built in, but I messed around with this to try and get errors to
// show in the validation summary without having to press the "submit" button. As it turns out,
// there was other code I made for a different form that worked without having to recreate
// the "remote" validation functions - setFocusOutvalidation.
$.validator.addMethod("remote", function (value, element, params) {
var email = {};
email[element.id] = value;
$.getJSON(params.url, email, function (result) {
if (result == false) {
var validator = $(element).closest("form").validate();
Em.displayValidationSummaryErrors(validator.errorList);
}
return result;
});
}, $.validator.messages.remote);
$.validator.unobtrusive.adapters.add("remote", ["url"], function (options) {
options.rules["remote"] = options.params;
if (options.message) options.messages["remote"] = options.message;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment