I'm working on an MVC4 app and needed some specific validation on a particular form. So I followed (several) tutorials on how to do this. Starting with a custom attribute:
public class CheckDuplicateElementNameAttribute :
ValidationAttribute, IClientValidatable
{
// Server side check omitted
public IEnumerable<ModelClientValidationRule>
GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule();
rule.ErrorMessage = this.ErrorMessage;
rule.ValidationType = "elementname";
yield return rule;
}
}
So then I add the attribute to the model's property like so:
public class HygieneElementModel
{
[CheckDuplicateElementName
(ErrorMessage="There is already an element with that name")]
public string ShortName { get; set; }
}
And finally added the js method to the page:
$(document).ready(function () {
jQuery.validator.addMethod('elementname', function (val, element) {
console.log('validating');
return false;
}, '');
jQuery.validator.unobtrusive.adapters.add('elementname', {}, function (options) {
options.rules['elementname'] = true;
options.messages['elementname'] = options.message;
});
jQuery.validator.unobtrusive.parse();
}
And the validation method completely fails to run. When I move the lines out of the document.ready
function and just have them run as soon as they are loaded, it works fine. Now, a lot of the examples I've followed - many of them from SO, show the addMethod calls being made from within document.ready, so why does mine not work this way?
Questions:
- Why is this?
- When are the default adapters registered and how do they parse the html before it is loades?
- Is there a risk that on a slow connection the validation adapter still won't be registered on time?
Version Detials
jQuery 1.11.0
jQuery.validation 1.8.1
Mircosoft.jQuery.Unobstrusive.Ajax 3.2.0
Mircosoft.jQuery.Unobstrusive.Validation 3.2.0