我不确定标题是否清楚。让我更好地解释一下:
我有两种模式:
1- GuestResponse.cs:
public class GuestResponse
{
[Required(ErrorMessage="Please enter your name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter your email address")]
[RegularExpression(".+\\@.+\\..+", ErrorMessage="Please enter a valid email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter your phone number")]
public string Phone { get; set; }
[Required(ErrorMessage = "Please especify wheter you will attend")]
public bool? WillAttend { get; set; }
}
2- CompanyGuestResponse.cs:
public class CompanyGuestResponse
{
[Required(ErrorMessage = "Please enter your company name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter your company email address")]
[RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please enter a valid email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter your company phone number")]
public string Phone { get; set; }
public IList<GuestResponse> GuestResponses { get; set;}
}
我还有一个针对CompanyGuestResponse模型的强类型视图,其中有一个表格,允许用户为属性GuestResponses提供输入。
我希望只有在表格的填充行被正确验证后才能提交表单(也就是说,不要尝试验证未填充的行)并且至少有一行正确填充。< / p>
我试图通过创建ViewModel validation for a List中描述的自定义注释来做到这一点,但没有成功(mvc只是忽略了列表注释并验证了GuestResponse类中的注释):
[EnsureOneElementAttribute(ErrorMessage = "At least a person is required")]
public IList<GuestResponse> GuestResponses { get; set;}
结果:
答案 0 :(得分:0)
我理解您要对模型本身进行验证,而不是对每个字段进行验证,因此您可以删除属性上的[Required]
属性,并在Action中验证是否填写了任何字段所以然后继续,添加一个错误,不要将它与任何字段
所以我告诉你在这个案例中删除注释并进行手动检查