3

好的,所以我有这些产品复选框,我想确保至少选择了一个产品。

为此,我的 ViewModel 包含:

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

视图仅包含:

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

该 EditorTemplate 包含:

@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)

自定义数据注解为:

[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;
    } 
}

jQuery部分是:

$.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;
});

因此,验证工作在服务器端。

但是,我如何让不显眼的验证工作?出于某种原因,

GetClientValidationRules没有将 HTML5 附加到复选框。

4

1 回答 1

1

我有一个与上面非常相似的实现,这个客户端 jquery 代码确实适用于作为模型一部分的一组复选框(附加到 HTML5)。它将从数据注释中传输 ErrorMessage。

    [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");

但是,就我而言,我还有另一个不属于模型的复选框集合。它是一个单独的表,因此它填充在用于生成复选框列表的 Viewbag 中。服务器端将不起作用,但客户端验证通过使用此 jquery 并将匹配的类名添加到复选框的 html 中起作用。

    $(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 });
});
于 2013-02-27T18:50:23.277 回答