我有一个自定义类:
public class BasicInfo
{
[Required(ErrorMessage = "First Name is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required.")]
public string LastName { get; set; }
}
public class ContactInfo
{
[Required(ErrorMessage = "Cell # is required.")]
public string CellNo { get; set; }
[Required(ErrorMessage = "Email is required.")]
public int Email { get; set; }
}
public class PErson
{
public BasicInfo bInfo { get; set; }
public ContactInfo cInfo { get; set; }
}
并使用此代码进行验证 - 取自:How does one do property validation of a C# class using Data Annotations in .NET Framework 3.5?
public static class Validator
{
// This could return a ValidationResult object etc
public static IEnumerable<string> Validate(object o)
{
Type type = o.GetType();
PropertyInfo[] properties = o.GetType().GetProperties();
foreach (var propertyInfo in properties)
{
object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(ValidationAttribute), inherit: true);
foreach (var customAttribute in customAttributes)
{
var validationAttribute = (ValidationAttribute)customAttribute;
bool isValid = validationAttribute.IsValid(propertyInfo.GetValue(o, BindingFlags.GetProperty, null, null, null));
if (!isValid)
{
yield return validationAttribute.ErrorMessage;
}
}
}
}
}
此代码适用于我的班级:
public class PErson
{
[Required(ErrorMessage = "First Name is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Cell # is required.")]
public string CellNo { get; set; }
[Required(ErrorMessage = "Email is required.")]
public int Email { get; set; }
}