gpt4 book ai didi

c# - 使用 Validator 类验证 DataAnnotations

转载 作者:IT王子 更新时间:2023-10-29 04:01:23 26 4
gpt4 key购买 nike

我正在尝试验证一个用 Validator class 数据注释装饰的类.

当属性应用于同一个类时,它工作正常。但是当我尝试使用元数据类时它不起作用。我应该对 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);

谢谢。

最佳答案

我在这里找到了答案: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);

关于c# - 使用 Validator 类验证 DataAnnotations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2050161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com