ASP.NET mVC 3.0 Validate MVCContrib CheckboxList

I implement a special validator to check if there is something checked:

public class AtLestOneRequiredAttribute : RequiredAttribute
    {
        public override bool IsValid(object value)
        {
            return (value != null);
        }
    }

    public class RequiredListValidator : DataAnnotationsModelValidator<AtLestOneRequiredAttribute>
    {
        private readonly string errorMessage;

        /// <summary>
        /// Initializes a new instance of the <see cref="EmailValidator"/> class.
        /// </summary>
        /// <param name="metadata">The metadata.</param>
        /// <param name="context">The context.</param>
        /// <param name="attribute">The attribute.</param>
        public RequiredListValidator(ModelMetadata metadata, ControllerContext context, AtLestOneRequiredAttribute attribute)
            : base(metadata, context, attribute)
        {
            this.errorMessage = attribute.ErrorMessage;
        }

        /// <summary>
        /// Retrieves a collection of client validation rules.
        /// </summary>
        /// <returns>A collection of client validation rules.</returns>
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = errorMessage,
                ValidationType = "atlestonerequired"
            };

            return new[] { rule };
        }        
    }

I also create Unobtrusive Validation Attributes for this select ( http://weblogs.asp.net/srkirkland/archive/2011/03/08/adding-unobtrusive-validation-to-mvccontrib-fluent-html.aspx )

Model:

[AtLestOneRequired(ErrorMessage="At least one selection required")]
        public IList<int> MyCheckBox{ get; set; }

View:

@this.CheckBoxList(x => x.MyCheckBox).Options(Model.MyCheckBoxes).IncludeUnobtrusiveValidationAttributes(Html)

As a result, I get this html with unobtrusive attributes in:

<div data-val="true" data-val-atlestonerequired="At least one selection required" id="MyCheckBox">
    <input id="MyCheckBox_0" name="MyCheckBox" type="checkbox" value="1"/>
    <label for="MyCheckBox_0" id="MyCheckBox_0_Label">A</label>
    <input id="MyCheckBox_1" name="MyCheckBox" type="checkbox" value="2"/>
    <label for="MyCheckBox_1" id="MyCheckBox_1_Label">B</label>
    <input id="MyCheckBox_2" name="MyCheckBox" type="checkbox" value="3"/>
    <label for="MyCheckBox_2" id="MyCheckBox_2_Label">C</label>
    <input id="MyCheckBox_3" name="MyCheckBox" type="checkbox" value="4"/>
    <label for="MyCheckBox_3" id="MyCheckBox_3_Label">D</label>
    ....
</div>

But my validaton is not working on the client side, what do I need to do to make it work? I think maybe I need to implement my own jQuery validaton method in this case, if it doesn't work by default?

tried to add this:

jQuery.validator.addMethod("atlestonerequired", function (value, element) {
             return (value != null);
         });

         jQuery.validator.unobtrusive.adapters.addBool('atlestonerequired');

does not work.

+3
source share
2 answers

. , , , , . , :

$(selector).find(":input[data-val=true]").each(function () {
  $jQval.unobtrusive.parseElement(this, true);
});

": " , input|select|textarea|button

, "div[data-val=true]" .

, , " ".

<div name="CheckBox" id="CheckBox">
  <input type="checkbox" data-val-cbrequired="Required" data-val="true" value="Default" name="CheckBox_0" id="CheckBox_0">
  <label for="CheckBox_0">Checkbox</label>
  <input type="checkbox" value="Yes" name="CheckBox_1" id="CheckBox_1">
  <label for="CheckBox_1">Yes</label>
  <input type="checkbox" value="No" name="CheckBox_2" id="CheckBox_2">
  <label for="CheckBox_2">No</label>
</div>

Jquery :

$.validator.unobtrusive.adapters.addBool("cbrequired", "required");
+1

. .

:

<input name="TermsNConditions" type="checkbox" id="TermsNConditions" tabindex="12" />

:

    [Required(ErrorMessage = "(Please accept the terms and conditions)")]
    [DefaultValue(0)]
    [RegularExpression(@"[^0]", ErrorMessage = "(Please accept the terms and conditions)")]
    public int AcceptTermsNConditions { get; set; }

<%:Html.HiddenFor(model=>model.AcceptTermsNConditions) %>

javascript , :

$(function () {
        $("#TermsNConditions").live("change", function () {
            if ($("#TermsNConditions").attr('checked')) {
                $("#AcceptTermsNConditions").val(1);
            }
            else {
                $("#AcceptTermsNConditions").val(0);
            }
        });
        if ($("#AcceptTermsNConditions").val() == 1) {
            $("#TermsNConditions").attr('checked', true);
        }
    });

script , .

0
source

All Articles