Created
November 15, 2012 06:02
-
-
Save timhobbs/4076889 to your computer and use it in GitHub Desktop.
jQuery "remote" validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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