gpt4 book ai didi

c# - Validator.TryValidateProperty 不工作

转载 作者:太空狗 更新时间:2023-10-29 17:42:30 25 4
gpt4 key购买 nike

我正在尝试实现 Validator.TryValidateProperty,即使存在 [Required] DataAnnotation,TryValidateProperty 也会返回有效响应。

这是我的客户部分类:

[MetadataType(typeof(Customer.Metadata))]
public partial class Customer : global::System.Data.Objects.DataClasses.EntityObject
{
...
private sealed class Metadata
{

[Required]
[SSNValidAttribute(ErrorMessage = "The SSN should be 9 numeric characters without any punctuation.")]
[DisplayName("SSN")]
public String SSN { get; set; }
...

这是返回 True 的代码:

...
var customer = new Customer();
customer.SSN = "";
var vc = new ValidationContext(customer, null, null);
vc.MemberName = "SSN";
var res = new List<ValidationResult>();
var result = Validator.TryValidateProperty(customer.SSN, vc, res);
...

最佳答案

好的,刚刚找到了处理密封的 MetadataType 类的解决方案。

var customer = new Customer();
TypeDescriptor.AddProviderTransparent
(new AssociatedMetadataTypeTypeDescriptionProvider
(customer.GetType()), customer.GetType());
customer.SSN = "";
var vc = new ValidationContext(customer, null, null);
vc.MemberName = "SSN";
var res = new List<ValidationResult>();
var result = Validator.TryValidateProperty(customer.SSN, vc, res);

我必须添加以下内容:

TypeDescriptor.AddProviderTransparent
(new AssociatedMetadataTypeTypeDescriptionProvider
(customer.GetType()), customer.GetType());

在此地址找到解决方案: http://forums.silverlight.net/forums/p/149264/333396.aspx

关于c# - Validator.TryValidateProperty 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6349645/

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