Nin*_*ner 2 validation asp.net-mvc asp.net-mvc-3
我的视图模型中有2个文本字段text1和text2.我需要验证是否输入了text1然后必须输入text2,反之亦然.如何在视图模型中进行自定义验证?
谢谢.
您可以在View模型上使用实现IValidatableObject(来自System.ComponentModel.DataAnnotations命名空间)进行服务器端验证:
public class AClass : IValidatableObject
{
public int Id { get; set; }
public string Name { get; set; }
public string SecondName { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if( (!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(SecondName)) || (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(SecondName)) )
yield return new ValidationResult("Name and Second Name should be either filled, or null",new[] {"Name","SecondName"});
}
}
Run Code Online (Sandbox Code Playgroud)
现在它确保是否设置了Name和SecondName,或者为null,那么model是有效的,否则,它不是.
| 归档时间: |
|
| 查看次数: |
4920 次 |
| 最近记录: |