Custom DataAnnotation for Multiple Checkboxes

£可爱£侵袭症+ 提交于 2019-12-24 00:19:00

问题


Alright, so I have these checkboxes of Products and I want to make sure at least one Product is selected.

To do this, my ViewModel contains:

[DisplayName(@"Product Line")]
[MinChecked(1)]
public List<CheckboxInfo> ActiveProducts { get; set; }

The View simply contains:

@Html.EditorFor(x => x.ActiveProducts)

That EditorTemplate contains:

@model Rad.Models.CheckboxInfo

@Html.HiddenFor(x => x.Value)
@Html.HiddenFor(x => x.Name)
@Html.CheckBoxFor(x => x.Selected)
@Html.LabelFor(x => x.Selected, Model.Name)

The custom dataannotation is:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class MinCheckedAttribute : ValidationAttribute, IClientValidatable
{
    public int MinValue { get; set; }

    public MinCheckedAttribute(int minValue)
    {
        MinValue = minValue;
        ErrorMessage = "At least " + MinValue + " {0} needs to be checked.";
    }

    public override string FormatErrorMessage(string propName)
    {
        return string.Format(ErrorMessage, propName);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        try
        {
            List<CheckboxInfo> valueList = (List<CheckboxInfo>)value;
            foreach (var valueItem in valueList)
            {
                if (valueItem.Selected)
                {
                    return ValidationResult.Success;
                }
            }
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
        catch (Exception x)
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "minchecked",
        };

        rule.ValidationParameters["minvalue"] = MinValue;

        yield return rule;
    } 
}

The jQuery part is:

$.validator.addMethod('minchecked', function (value, element, params) {
    var minValue = params['minvalue'];
    alert(minValue);
    $(element).each(function () {
        if ($(this).is(':checked')) {
            return true;
        }
    });
    return false;
});
$.validator.unobtrusive.adapters.add('minchecked', ['minvalue'], function (options) {
    options.messages['minchecked'] = options.message;
    options.rules['minchecked'] = options.params;
});

So, the validation works server side.

But, how do I get the unobtrusive validation to work? For some reason, the

GetClientValidationRules is not attaching the HTML5 to the checkboxes.


回答1:


I have a very similar implementation as above and this client side jquery code does work (attaches to the HTML5) for a group of checkboxes that are part of the model. It will transfer the ErrorMessage from the data annotations.

    [Display(Name = "Location1")]
    [CheckAtLeastOne(ErrorMessage = "Must check at least one Location")]
    public DateTime Location1 { get; set; }

    [Display(Name = "Location2")]
    public DateTime Location2 { get; set; }

    [Display(Name = "Location3")]
    public DateTime Location3 { get; set; }

    [Display(Name = "Location4")]
    public DateTime Location4 { get; set; }

    $(function () {
    $.validator.addMethod("checkatleastone", function (value, element) {
        var tag = $("#editform-locations").find(":checkbox");
        return tag.filter(':checked').length;
    });
});
$.validator.unobtrusive.adapters.addBool("checkatleastone");

However, in my case, I have another collection of checkboxes that are not part of the model. It is a separate table so it is populated in a Viewbag which is used to generate a list of checkboxes. The server-side will not work but the client-side validation does work by using this jquery and adding the matching class name to the html for the checkboxes.

    $(function () {
    $.validator.addMethod("CheckOneCategory", function (value, element) {
        var tag = $("#editform-categories").find(":checkbox");
        return tag.filter(':checked').length;
    }, "Select at least one Product/Service Category");
    $.validator.addClassRules("require-one-category", { CheckOneCategory: true });
});


来源:https://stackoverflow.com/questions/14244241/custom-dataannotation-for-multiple-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!