我尝试根据需要,最大长度,默认值等属性验证类。我不想确定对象是否有效,我还想尝试通过修剪,初始化来修正值(null为""如果剩下必填字段例如,空)
我确实发现了一些关于课程手动验证的帖子。
http://odetocode.com/Blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx
http://aboutdev.wordpress.com/2009/12/20/poor-mans-validation/
但不确定如何更正它们的对象值无效。
同样这是一个简单的POCO类,我唯一关心的是验证类,如果我想要完成的是不可能的话,我总是可以手动验证每个属性。建议欢迎。
目前我正在尝试使用indexer和Validator.TryValidateObject()完成此操作,如下所示:
class Customer
{
public int Id { get; set; }
[Required(ErrorMessage = "required"), MaxLength(250)]
public string Name { get; set; }
[DefaultValue('N')]
public char Active { get; set; }
public object this[string propertyName]
{
get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
}
}
class Program
{
static void Main(string[] args)
{
var customer = new Customer { Id = 1, Active = 'Y', Name = null };
var context = new ValidationContext(customer, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(customer, context, results); // false
foreach (var result in results)
{
object value = customer[result.MemberNames.First().ToString()];
switch (result.ErrorMessage)
{
case "required" :
customer[result.MemberNames.First().ToString()] = "John Smith";
break;
default:
break;
}
}
results.Clear();
isValid = Validator.TryValidateObject(customer, context, results); // true
}
}