【问题标题】:Validation Attributes MVC 2 - checking one of two values验证属性 MVC 2 - 检查两个值之一
【发布时间】:2010-07-21 10:01:54
【问题描述】:

有人可以帮我解决这个问题吗?我试图弄清楚如何检查表单上的两个值,必须填写两项中的一项。如何进行检查以确保已输入一项或两项?

我在 ASP.NET MVC 2 中使用视图模型。

下面是一小段代码:

观点:

Email: <%=Html.TextBoxFor(x => x.Email)%>
Telephone: <%=Html.TextBoxFor(x => x.TelephoneNumber)%>

视图模型:

    [Email(ErrorMessage = "Please Enter a Valid Email Address")]
    public string Email { get; set; }

    [DisplayName("Telephone Number")]
    public string TelephoneNumber { get; set; }

我希望提供这些详细信息中的任何一个。

感谢您的任何指点。

【问题讨论】:

    标签: validation asp.net-mvc-2 attributes viewmodel


    【解决方案1】:

    您可以使用与作为 File->New->ASP.NET MVC 2 Web 应用程序一部分的PropertiesMustMatch 属性大致相同的方式来执行此操作。

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public sealed class EitherOrAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "Either '{0}' or '{1}' must have a value.";
        private readonly object _typeId = new object();
    
        public EitherOrAttribute(string primaryProperty, string secondaryProperty)
            : base(_defaultErrorMessage)
        {
            PrimaryProperty = primaryProperty;
            SecondaryProperty = secondaryProperty;
        }
    
        public string PrimaryProperty { get; private set; }
        public string SecondaryProperty { get; private set; }
    
        public override object TypeId
        {
            get
            {
                return _typeId;
            }
        }
    
        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                PrimaryProperty, SecondaryProperty);
        }
    
        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            object primaryValue = properties.Find(PrimaryProperty, true /* ignoreCase */).GetValue(value);
            object secondaryValue = properties.Find(SecondaryProperty, true /* ignoreCase */).GetValue(value);
            return primaryValue != null || secondaryValue != null;
        }
    }
    

    这个函数的关键部分是判断两个参数之一是否有值的 IsValid 函数。

    与普通的基于属性的属性不同,它应用于类级别并且可以像这样使用:

    [EitherOr("Email", "TelephoneNumber")]
    public class ExampleViewModel
    {
        [Email(ErrorMessage = "Please Enter a Valid Email Address")]
        public string Email { get; set; }
    
        [DisplayName("Telephone Number")]
        public string TelephoneNumber { get; set; }
    }
    

    您应该可以根据需要添加任意数量的表单,但如果您想强制他们在两个以上的框中(例如电子邮件、电话或传真)中输入一个值,那么您可以可能最好将输入更改为更多的值数组并以这种方式解析它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 2011-07-19
      相关资源
      最近更新 更多