使用Data Annotations进行手动验证
August 12, 2013
author: feeldesignstudio.com
author: feeldesignstudio.com
DataAnnotations在ASP.NET MVC中非常好用,但是其他时候,比如控制台程序,我们怎么来使用它呢。
直接上代码,一个超简单的类:
public class Customer
{
[Required]
public string Name { get; set; }
[Required]
public string Phone { get; set; }
[Required]
public string Email { get; set; }
}
下面是验证的代码:
var cust = new Customer();
var context = new ValidationContext(cust, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(cust, context, results);
if (!isValid)
{
foreach (var validationResult in results)
{
Console.WriteLine(validationResult.ErrorMessage);
}
}
实现IValidatableObject,也可以:
public class Customer : IValidatableObject
{
[Required]
public string Name { get; set; }
[Required]
public string Phone { get; set; }
[Required]
public string Email { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
...
}
}
http://jnoodle.github.io/2013/08/data-annotations-manual
http://www.feeldesignstudio.com/2013/08/data-annotations-manual
© 未标明转载均为原创,在满足创作共用版权协议的基础上欢迎转载,请注明作者和出处链接
Tips: 评论也可以匿名哦,不一定注册的,只需要勾选匿名评论(I'd rather post as a guest)即可