使用Validator类验证DataAnnotations

Pab*_*ote 37 .net c# validation .net-4.0 data-annotations

我正在尝试使用Validator类验证使用数据注释修饰的.

当属性应用于同一个类时,它可以正常工作.但是当我尝试使用元数据类时,它不起作用.我应该对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; }
}
Run Code Online (Sandbox Code Playgroud)

这不起作用:

[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; }
}
Run Code Online (Sandbox Code Playgroud)

这是我验证实例的方式:

ValidationContext context = new ValidationContext(p, null, null);
List<ValidationResult> results = new List<ValidationResult>();

bool valid = Validator.TryValidateObject(p, context, results, true);
Run Code Online (Sandbox Code Playgroud)

谢谢.

Jer*_*ald 46

我在这里找到答案:http://forums.silverlight.net/forums/p/149264/377212.aspx

MVC识别MetaDataType属性,但其他项目则不识别.在验证之前,您需要手动注册元数据类:

TypeDescriptor.AddProviderTransparent(
            new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Persona), typeof(Persona_Validation)), typeof(Persona));

ValidationContext context = new ValidationContext(p, null, null);
List<ValidationResult> results = new List<ValidationResult>();

bool valid = Validator.TryValidateObject(p, context, results, true);
Run Code Online (Sandbox Code Playgroud)

  • 就是这样!:) (3认同)