我试图验证装饰有Validator class的数据注释的类。使用验证程序类验证DataAnnotations
当属性应用于同一个类时,它工作正常。但是当我尝试使用元数据类时,它不起作用。有什么我应该用Validator做的,所以它使用元数据类?下面是一些代码..
这个工程:
public class Persona
{
[Required(AllowEmptyStrings = false, ErrorMessage = "El nombre es obligatorio")]
public string Nombre { get; set; }
[Range(0, int.MaxValue, ErrorMessage="La edad no puede ser negativa")]
public int Edad { get; set; }
}
这并不工作:
[MetadataType(typeof(Persona_Validation))]
public class Persona
{
public string Nombre { get; set; }
public int Edad { get; set; }
}
public class Persona_Validation
{
[Required(AllowEmptyStrings = false, ErrorMessage = "El nombre es obligatorio")]
public string Nombre { get; set; }
[Range(0, int.MaxValue, ErrorMessage = "La edad no puede ser negativa")]
public int Edad { get; set; }
}
这是我的验证情况:
ValidationContext context = new ValidationContext(p, null, null);
List<ValidationResult> results = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(p, context, results, true);
感谢。
我不能System.ComponentModel.DataAnnotations(MVC 2.0) 我做得不对内找到ValidationContext? – Myster 2010-07-21 23:24:56
@Myster检查项目中是否引用了System.ComponentModel.DataAnnotations.dll。 – Pablote 2010-07-24 02:33:16
只需使用[gist](https://gist.github.com/JimmyBoh/b7c135820c18a06648a5)(扩展方法),你可以调用p.Validate() – 2017-05-05 03:02:39