Custom unobtrusive MVC4 validator not working

not sure what is wrong. The syntax seems correct ... but it still doesn't work on the client side. If I submit the form, I get a confirmation on the server side, on the client side nothing ...

Here is the code that is on the page:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script> <script type="text/javascript"> // we add a custom jquery validation method (function ($) { $.validator.addMethod('additive', function (value, element, params) { //just return false to test it. return false; }); // and an unobtrusive adapter $.validator.unobtrusive.adapters.add("additive", ["field2", "field3", "field4"], function (options) { var params = { field2: options.params.field2, field3: options.params.field3, field4: options.params.field4 }; options.rules['additive'] = params; if (options.message) { options.messages['additive'] = options.message; } }); }) (jQuery); </script> 

Here is the part that is on the validator that is associated with the client side (IClientValidatable):

 public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { ModelClientValidationRule rule = new ModelClientValidationRule { ValidationType = "additive", ErrorMessage = "ERROR MESSAGE" }; rule.ValidationParameters.Add("field2", propName2); rule.ValidationParameters.Add("field3", propName3); rule.ValidationParameters.Add("field4", propName4); yield return rule; } 

The model is designed as follows:

 [SumValidation("OtherField2...")] public int MyField { get; set; } 

When the field is displayed, all this is on the whole server in terms of data-xxx attributes. Only this particular client check does not work. Does anyone see what I'm missing?

+3
source share
1 answer

figured it out. If someone comes across this. User check added too late on the page. After I moved javascript to a custom validator in the section of the _Layout.cshtml chapter, it started working.

So, if your script looks right, you need to check a good place.

Another task is to run $ .validator.unobtrusive.parse ('form'); which reloads all validators.

+7
source

All Articles