Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom jQuery unobtrusive validator to check if either a input is filled or a checkbox is checked.
@{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
@using (Html.BeginForm())
{
<input type="hidden" class="include-validation" name="test" data-val="true" data-val-requiredoptout="verplicht veld"
data-val-requiredoptout-optoutfieldselector="#testcheck" data-val-requiredoptout-requiredfieldselector="#test2" />
<input type="text" name="test2" id="test2" />
<input type="checkbox" name="testcheck" id="testcheck" />
<span data-valmsg-for="test" data-valmsg-replace="true"></span>
<br />
<button type="submit" value="submit" class="btn btn-primary" >Submit</button>
}
$.validator.setDefaults({
ignore: ":hidden:not(.include-validation)",
// any other default options and/or rules
});
jQuery.validator.addMethod("requiredoptout", function (value, element, params) {
return $(params[1]).val().length > 0 || $(params[0]).is(':checked');
});
jQuery.validator.unobtrusive.adapters.add("requiredoptout", ["optoutfieldselector", "requiredfieldselector"], function (options) {
options.rules["requiredoptout"] = [options.params.optoutfieldselector,options.params.requiredfieldselector];
options.messages["requiredoptout"] = options.message;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment