MVC3不显眼的验证组输入并突出显示组中的所有字段

时间:2012-08-24 06:28:11

标签: c# asp.net-mvc validation

我的问题与之前在以下链接中提出的问题非常相似,

MVC3 unobtrusive validation group of inputs

基本上我需要验证3个或更多输入字段(至少需要一个)。例如,我有电子邮件,传真,地址。定义如下:

public class MyViewModel
{ 
    public string Email { get; set; }
    public string Fax { get; set; }
    public Address Address { get; set; }
}

public class Address 
{ 
    public string Street { get; set; }
    public string Suburb { get; set; }
}

我需要填写Email,Fax或Address.Suburb,如果失败,我希望所有字段都突出显示而不是只有一个字段(这是前一个链接中包含的解决方案)。

请注意,我已经完成了所有服务器端验证工作,我只需要知道如何使用MVC3在我的客户端进行此操作。

1 个答案:

答案 0 :(得分:2)

您可以尝试在所有属性上应用AtLeastOneRequired属性:

public class MyViewModel
{
    [AtLeastOneRequired("Email", "Fax", "Phone", ErrorMessage = "At least Email, Fax or Phone is required")]
    public string Email { get; set; }

    [AtLeastOneRequired("Email", "Fax", "Phone", ErrorMessage = "At least Email, Fax or Phone is required")]
    public string Fax { get; set; }

    [AtLeastOneRequired("Email", "Fax", "Phone", ErrorMessage = "At least Email, Fax or Phone is required")]
    public string Phone { get; set; }
}