I have an ajax form on a partial view which uses a custom unobtrusive validator for an either/or style validator (described here). My custom validator works fine when used on a form which is not loaded via an ajax call. This partial however, is loaded via an @Ajax.ActionLink
call which loads the partial into the containing view.
Containing view:
<div id="form-container">
@Html.Action("Login", "MyController") //Initial state. Loads Login.cshtml partial view
</div>
Login.cshtml partial:
//contains markup for login form fields, but also this link to the signup partial (Signup.cshtml)
@Ajax.ActionLink("click here", "Signup", "MyController",
new AjaxOptions
{
OnSuccess = "initializeValidation();",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "form-container"
})
Signup.cshtml partial:
@model SignupViewModel
<div>
@using (Ajax.BeginForm("Signup", "MyController", new AjaxOptions
{
OnSuccess = "initializeValidation();",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "form-container"
}))
{
<p>
@Html.LabelFor(m=>m.Username)
@Html.EditorFor(m=>m.Username)
@Html.ValidationMessageFor(m=>m.Username)
</p>
<p>
@Html.LabelFor(m=>m.Email)
@Html.EditorFor(m=>m.Email)
@Html.ValidationMessageFor(m=>m.Email)
</p>
<input type="submit" value="Next"/>
}
</div>
My javascript method initializeValidation()
has the following code to reset the unobtrusive validation:
$('form').removeData("validator");
$('form').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('form');
The problem I have is that the custom validator does not work on a form which is loaded via @Ajax.ActionLink. I looked at this question and this question which correctly reset the standard unobtrusive validation methods, but I can't figure out how to reset the custom one. The custom validation method and its unobtrusive adapter is configured with the code below
$.validator.addMethod("eitherorrequired", function (value, element, params) {
var otherValue = $(params).val();
return value != "" || otherValue != "";
});
$.validator.unobtrusive.adapters.add("eitherorrequired", ["dependentproperty"], function (options) {
options.rules["eitherorrequired"] = "#" + options.params.dependentproperty;
options.messages["eitherorrequired"] = options.message;
});
I've tried including this within the initializeValidation()
method, but it still does not work.