简体   繁体   English

DataType(DataType.PhoneNumber)和PhoneAttribute有什么区别

[英]What's the difference between DataType(DataType.PhoneNumber) & PhoneAttribute

What's the difference between using DataType Attribute and passing in a value of DataType.Phone and the Phone Attribute which inherits from DataType and automatically sets DataType.Phone ? 什么是两者的区别: DataType属性和传递的价值DataType.PhonePhone属性从继承DataType ,并自动设置DataType.Phone

Is there any difference between these two classes? 这两类之间有什么区别吗?

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

TLDR : [Phone] provides validation logic while [DataType] does not TLDR[Phone]提供验证逻辑,而[DataType]不提供

The inheritance chain looks like this: 继承链如下所示:

Attribute
ValidationAttribute ValidationAttribute
DataTypeAttribute DataTypeAttribute
PhoneAttribute PhoneAttribute

So both are instances of ValidationAttribute , however both don't provide Validation out of the box. 因此,这两个都是ValidationAttribute实例,但是都没有开箱即用地提供Validation。 The DataType base class just provides the structure for assigning an enum DataType and leaves overriding the validation up to the caller DataType基类仅提供用于分配enum DataType的结构,而将重写验证留给调用方

DataType - According to the Docs: DataType -根据文档:

When you apply the DataTypeAttribute attribute to a data field you must do the following: 当您将DataTypeAttribute属性应用于数据字段时,必须执行以下操作:

  • Issue validation errors as appropriate. 发出适当的验证错误。

DataType - According to the Source Code: DataType根据源代码:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = false)]
public class DataTypeAttribute : ValidationAttribute
{
    /// <summary> Override of <see cref="ValidationAttribute.IsValid(object)" /> </summary>
    /// <remarks>This override always returns <c>true</c>.  Subclasses should override this to provide the correct result.</remarks>
    /// <param name="value">The value to validate</param>
    /// <returns>Unconditionally returns <c>true</c></returns>
    /// <exception cref="InvalidOperationException"> is thrown if the current attribute is ill-formed.</exception>
    public override bool IsValid(object value)
    {
        EnsureValidDataType();

        return true;
    }
 }

Aside : Since you are required to override IsValid , I'm not sure why .NET didn't mark the class and property as abstract to guarantee an implementation programmatically. 另外 :由于需要重写IsValid ,因此我不确定.NET为什么没有将类和属性标记为abstract来以编程方式保证实现。

PhoneAttribute - Validation Logic PhoneAttribute验证逻辑

So if you do want to provide validation, and you're using .NET 4.5+ or .NET Core, you can use the [Phone] attribute, but the mechanism for validation has changed over time as well and also you might have a different set of rules on what constitutes valid input for your business process. 因此,如果您确实想提供验证,并且您正在使用.NET 4.5+或.NET Core,则可以使用[Phone]属性,但是验证机制也随时间而改变,并且您可能会有所不同关于什么构成业务流程的有效输入的一组规则。

.NET Framework initially used the following regular expression: .NET Framework最初使用以下正则表达式:

const string pattern = @"^(\+\s?)?((?<!\+.*)\(\+?\d+([\s\-\.]?\d+)?\)|\d+)([\s\-\.]?(\(\d+([\s\-\.]?\d+)?\)|\d+))*(\s?(x|ext\.?)\s?\d+)?$";

But this was deprecated in .NET Framework 4.7.2 per this change description , likely due to injection/security concerns layed out in the Regular Expression Best Practices from unconstrained input. 但是, 此更改描述在.NET Framework 4.7.2中已弃用此消息 ,这可能是由于正则表达式最佳实践中不受约束的输入所涉及的注入/安全问题。

If you want to continue using regex validation, you'd have to set the following in the configuration > appsettings section of your .config file: 如果要继续使用正则表达式验证,则必须在.config文件的configuration > appsettings部分中进行以下设置:

<add key="dataAnnotations:dataTypeAttribute:disableRegEx" value="false"/>

The Test project includes a sample of what inputs should pass/fail according to PhoneAttributeTests.cs and here's a Regexr page if you want to test out matching input against the (deprecated) regular expression validation engine. 测试项目包括根据PhoneAttributeTests.cs输入应该通过/失败的输入的样本,如果要根据(不建议使用的)正则表达式验证引擎测试匹配的输入,则这是Regexr页面


Here's some links for source code and documentation for different flavors of .NET: 这是一些用于各种.NET版本的源代码和文档的链接:

                  | .NET Core         | .NET Core 2.1  |  .NET 4.7.2     | .NET           |
------------------|-------------------|----------------|-----------------|----------------|
DataTypeAttribute | github.com/dotnet | source.dot.net | referencesource | docs.microsoft |
PhoneAttribute    | github.com/dotnet | source.dot.net | referencesource | docs.microsoft |

Note : The current docs for [Phone] mistakenly remarks that the validation uses Regular Expressions, which has not been true since 4.7.2+ or anywhere in .NET core, so I've submitted this PR to update 注意[Phone]的当前文档错误地指出验证使用的是正则表达式,自4.7.2+或.NET Core中的任何地方以来都是不正确的,因此我已提交此PR进行更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM