Con un po 'di riflessione, è possibile creare il proprio validatore che esegue la scansione del ValidationAttributes
sulle proprietà che avete. Potrebbe non essere una soluzione perfetta, ma se si è limitati a utilizzare .NET 3.5, questa sembra una soluzione leggera, si spera che si ottenga l'immagine.
static void Main(string[] args)
{
Person p = new Person();
p.Age = 4;
var results = Validator.Validate(p);
results.ToList().ForEach(error => Console.WriteLine(error));
Console.Read();
}
// Simple Validator class
public static class Validator
{
// This could return a ValidationResult object etc
public static IEnumerable<string> Validate(object o)
{
Type type = o.GetType();
PropertyInfo[] properties = type.GetProperties();
Type attrType = typeof (ValidationAttribute);
foreach (var propertyInfo in properties)
{
object[] customAttributes = propertyInfo.GetCustomAttributes(attrType, 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 = "Name is required!")]
public string Name { get; set; }
[Range(5, 20, ErrorMessage = "Must be between 5 and 20!")]
public int Age { get; set; }
}
Questo stampa il seguente alla console: è richiesto
Nome!
Deve essere compreso tra 5 e 20!
fonte
2013-06-24 22:55:34
non so se c'è qualcosa di simile in .NET 3.5, ma se siete disposti a utilizzare un'altra libreria, Enterprise Application Block di Microsoft contiene una Validation Application Block che contiene un validatore classe che può validare oggetti decorati con DataAnnotations. –