一个ASP.NET MVC验证,以确保至少有一个复选框被选中 [英] An ASP.NET MVC validator to make sure at least one checkbox is checked

查看:191
本文介绍了一个ASP.NET MVC验证,以确保至少有一个复选框被选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我已经创建了一个数据传输对象从一个网页表单接收数据的ASP.NET MVC 2项目。形式有两组它的复选框。我要验证的对象,以确保各组中的复选框中的至少一个被选中。

I have an ASP.NET MVC 2 project in which I've created a data transfer object to receive data from a web page form. The form has two groups of checkboxes on it. I want to validate the object to make sure that at least one of the checkboxes in each group is checked.

我做在服务器端验证,以便用户将不能够破解周围的任何客户端验证。 (我将添加客户端验证与jQuery以后。这很容易)

I'm doing the validation on the server side so that a user won't be able to hack around any client-side validation. (I will add client-side validation with jQuery later; that's easy.)

我的理解是,我要创建自己的自定义ValidationAttribute我的数据传输对象类,但我不知道如何创建和使用一个可以接受的复选框的任意属性列表,以确保至少有一个它们是真实的。我猜我将不得不调用属性如下:

My understanding is that I have to create my own custom ValidationAttribute for my data transfer object class, but I don't understand how to create and use one that can accept an arbitrary list of checkbox properties to make sure that at least one of them is true. I am guessing I will have to call the attributes like this:

[AtLeastOneCheckbox("set1check1", "set1check2", "set1check3",
    ErrorMessage = "You must check at least one checkbox in set 1.")]
[AtLeastOneCheckbox("set2check1", "set2check2", "set2check3", "set2check4", "set2check5",
    ErrorMessage = "You must check at least one checkbox in set 2.")]
public class MyFormDTO
{
    ...
}

将AtLeastOneCheckboxAttribute实施什么样的?

What would the implementation of AtLeastOneCheckboxAttribute look like?

还是有不同的方式,我应该做这种验证?

Or is there a different way that I should do this kind of validation?

推荐答案

如果你有几个复选框组,你只需要可待因属性几次。

[AttributeUsage( AttributeTargets.Class)]
public class AtLeastOneCheckboxAttribute : ValidationAttribute
{
    private string[] _checkboxNames;

    public AtLeastOneCheckboxAttribute(params string[] checkboxNames)
    {
        _checkboxNames = checkboxNames;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var propertyInfos = value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(x=>_checkboxNames.Contains(x.Name));

        var values = propertyInfos.Select(x => x.GetGetMethod().Invoke(value, null));
        if (values.Any(x => Convert.ToBoolean(x)))
            return ValidationResult.Success;
        else
        {
            ErrorMessage = "At least one checkbox must be selected";
            return new ValidationResult(ErrorMessage);
        }
    }
}


更新

因为你已经发现了,类级别的验证调用后才能全部属性通过。为了得到错误,只是使用空字符串作为关键

as you have found out, class-level validation is called only after all properties pass. In order to get the error, just use empty string as the key.

这篇关于一个ASP.NET MVC验证,以确保至少有一个复选框被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆