I wrote a custom validator using MVC DataAnnotations and the jQuery unobtrusive javascript library. It's working great. The only problem I have now is that after the initial validation, if the user edit's the field, it's firing the validator on each keystroke. Since the validator hits a web service to validate the input, I'd prefer that it always just validate the input when the user moves off of the field or the form is submitted. Is there a way to change this behavior? Here's my code:
<script type="text/javascript">
$.validator.addMethod("validate_zipcode", function (value, element) {
if (value == null || value.length == 0) {
return true;
}
var isValid = false;
$.ajax({
async: false,
dataType: "json",
url: "/api/iszipvalid/" + value,
success: function (response) {
isValid = response;
}
});
return isValid;
});
$.validator.unobtrusive.adapters.addBool('zipcode', 'validate_zipcode');
</script>
I'm not positive this will work in conjunction with ASP.NET MVC (I'll whip up a test project later), but validate allows you to set defaults for all instances of validate like this:
If you can add that line before MVC gets a handle on
validate
it might work, but it'll disableonkeyup
for all fields in all forms (judging by your post, it seems like this would be ok).Hope that helps.