关于 DataType 如何工作的数据注释有很好的参考吗?

发布于 2024-08-03 05:46:18 字数 1711 浏览 4 评论 0原文

我有一个客户类,它同时具有 PhoneNumber 和 Email 属性。使用 DataAnnotations,我可以用 DataType 验证属性来装饰属性,但我看不到这给我带来了什么。

例如:

 [DataType(DataType.PhoneNumber)]
 public string PhoneNumber {get; set;}

我有一个单元测试,将“1515999A”分配给该属性。当我单步执行验证运行程序时,该值被认为对电话号码有效。我本以为这应该是无效的。

我用谷歌搜索了一些,但找不到关于各种枚举数据类型实际捕获的内容的合适解释。有什么值得参考的地方吗?

编辑:

这是我用于验证运行程序的内容......

    public virtual XLValidationIssues ValidateAttributes<TEntity>(TEntity entity)
    {
        var validationIssues = new XLValidationIssues();

        // Get list of properties from validationModel
        var props = entity.GetType().GetProperties();

        // Perform validation on each property
        foreach (var prop in props)
            ValidateProperty(validationIssues, entity, prop);

        // Return the list
        return validationIssues;
    }

    protected virtual void ValidateProperty<TEntity>(XLValidationIssues validationIssues, TEntity entity, PropertyInfo property)
    {
        // Get list of validator attributes
        var validators = property.GetCustomAttributes(typeof(ValidationAttribute), true);
        foreach (ValidationAttribute validator in validators)
            ValidateValidator(validationIssues, entity, property, validator);
    }

    protected virtual void ValidateValidator<TEntity>(XLValidationIssues validationIssues, TEntity entity, PropertyInfo property, ValidationAttribute validator)
    {
        var value = property.GetValue(entity, null);
        if (!validator.IsValid(value))
            validationIssues.Add(new XLValidationIssue(property.Name, value, validator.FormatErrorMessage(property.Name, value)));
    }

I have a customer class which has both PhoneNumber and Email properties. Using DataAnnotations I can decorate the properties with DataType validation attributes, but I cannot see what that is getting me.

For example:

 [DataType(DataType.PhoneNumber)]
 public string PhoneNumber {get; set;}

I have a unit test that assigned "1515999A" to this property. When I step through the validation runner the value is considered valid for a phone number. I would have thought this should be invalid.

I google'd around some but couldn't find a decent explanation of what the various enumerated DataTypes actually catch. Is there a worthwhile reference somewhere?

Edit:

Here are the guts of what I'm using for a validation runner...

    public virtual XLValidationIssues ValidateAttributes<TEntity>(TEntity entity)
    {
        var validationIssues = new XLValidationIssues();

        // Get list of properties from validationModel
        var props = entity.GetType().GetProperties();

        // Perform validation on each property
        foreach (var prop in props)
            ValidateProperty(validationIssues, entity, prop);

        // Return the list
        return validationIssues;
    }

    protected virtual void ValidateProperty<TEntity>(XLValidationIssues validationIssues, TEntity entity, PropertyInfo property)
    {
        // Get list of validator attributes
        var validators = property.GetCustomAttributes(typeof(ValidationAttribute), true);
        foreach (ValidationAttribute validator in validators)
            ValidateValidator(validationIssues, entity, property, validator);
    }

    protected virtual void ValidateValidator<TEntity>(XLValidationIssues validationIssues, TEntity entity, PropertyInfo property, ValidationAttribute validator)
    {
        var value = property.GetValue(entity, null);
        if (!validator.IsValid(value))
            validationIssues.Add(new XLValidationIssue(property.Name, value, validator.FormatErrorMessage(property.Name, value)));
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

携余温的黄昏 2024-08-10 05:46:18

我在网上找不到太多关于 DataType.PhoneNumber 的信息,但我确实找到了这个:

http://forums.asp.net/p/1370546/2863383.aspx

在 RTM 版本中,
DataType.EmailAddress 仅用于
标记自己的数据类型
使用。

我想了解更多信息,因此我拿出 Red Gate 的 .NET Reflector 并开始挖掘。

看看 DataTypeAttribute 类,Joseph Daigle 说得很对——每个 DataType 属性都不进行任何验证; is 总是返回 true(即“有效”)。对于某些数据类型,会完成一些自定义显示字符串格式。然而,电话号码几乎没有动过。

因此,我研究了这个问题的可能解决方案。根据我的发现, this 看起来是最好的:

public class EvenNumberAttribute : ValidationAttribute
{
    public EvenNumberAttribute() : base(() => Resource1.EvenNumberError) { }
    public EvenNumberAttribute(string errorMessage) : base(() => errorMessage) { }

    protected override ValidationResult IsValid(object value, 
        ValidationContext validationContext)
    {
        if (value == null)
        {
            return ValidationResult.Success;
        }

        int convertedValue;
        try
        {
            convertedValue = Convert.ToInt32(value);
        }
        catch (FormatException)
        {
            return new ValidationResult(Resource1.ConversionError);
        }

        if (convertedValue % 2 == 0)
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
    }
}

当然,它可以验证数字是奇数还是偶数。您可以为电话号码、电子邮件等编写一个实际上执行验证的自定义验证属性。

I couldn't find much on the web about DataType.PhoneNumber, but I did find this:

http://forums.asp.net/p/1370546/2863383.aspx

In the RTM release, the
DataType.EmailAddress is only used to
mark the type of data for your own
use.

I wanted to find out a bit more, so I pulled out Red Gate's .NET Reflector and started digging around.

Looking at the DataTypeAttribute class, Joseph Daigle is spot on -- each DataType attribute doesn't do any validation; is always returns true (i.e. "valid"). On some data types, some custom display string formatting is done. Phone numbers, however, are pretty much left untouched.

So, I looked into possible solutions to this problem. From what I've found, this looks like the best:

public class EvenNumberAttribute : ValidationAttribute
{
    public EvenNumberAttribute() : base(() => Resource1.EvenNumberError) { }
    public EvenNumberAttribute(string errorMessage) : base(() => errorMessage) { }

    protected override ValidationResult IsValid(object value, 
        ValidationContext validationContext)
    {
        if (value == null)
        {
            return ValidationResult.Success;
        }

        int convertedValue;
        try
        {
            convertedValue = Convert.ToInt32(value);
        }
        catch (FormatException)
        {
            return new ValidationResult(Resource1.ConversionError);
        }

        if (convertedValue % 2 == 0)
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
    }
}

Of course, that validates whether a number is odd or even. You could write a custom validation attribute for PhoneNumber, Email, etc. that actually does validation.

日裸衫吸 2024-08-10 05:46:18

电话号码、邮政编码应使用 RegularExpressionAttribute Class

Phone number, zip should be validated with the RegularExpressionAttribute Class

始终不够爱げ你 2024-08-10 05:46:18

DataTypeAttribute 是一个ValidationAttribute。但它总是返回 true...所以它不做任何真正的验证。

(我知道 3.5 是这样,我不确定 4.0 是否也这样)

The DataTypeAttribute is a ValidationAttribute. But it ALWAYS returns true... so it doesn't do any real validation.

(I know this is true for 3.5, I'm not sure if it's true for 4.0)

一抹淡然 2024-08-10 05:46:18

也许是因为电话号码可以包含字母? wiki

Maybe its because phone numbers can contain letters? wiki

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文