免责声明: 这只是我阅读后的理解源代码 https://github.com/Microsoft/referencesource/tree/master/System.ComponentModel.DataAnnotations/DataAnnotations(欢迎指正)
(数据类型属性 https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/DataTypeAttribute.cs) is a ValidationAttribute
(源自ValidationAttribute
)并且你需要传递它Enum https://github.com/dotnet/corefx/blob/master/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DataType.cs(也称为DataType
).
验证属性需要重写IsValid
方法,在模型绑定上执行,需要判断值是否有效。自定义验证器如下所示:
public class CustomValidator : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// do some validation
if (/* validation passes */)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Validation message...");
}
}
}
现在,回到DataTypeAttribue
(这是一个验证属性),你需要传递它DataType
enum:
public enum DataType
{
Custom = 0,
DateTime = 1,
Date = 2,
Time = 3,
Duration = 4,
PhoneNumber = 5,
Currency = 6,
Text = 7,
Html = 8,
MultilineText = 9,
EmailAddress = 10,
Password = 11,
Url = 12,
ImageUrl = 13,
CreditCard = 14,
PostalCode = 15,
Upload = 16
}
据我所知,这一切DataTypeAttribtue
是添加一些格式DataType.Date
, DataType.Time
and DataType.Currency
...(还设置_dataTypeStrings
)
此外,您还有验证属性,例如电子邮件地址属性 https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/EmailAddressAttribute.cs, 电话属性 https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/PhoneAttribute.cs, 网址属性 https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/UrlAttribute.cs等源自DataTypeAttribute
并对这些特定类型进行额外验证:
现在您可以这样使用这些验证属性:
public class MyModel
{
[Phone] // <- executes the IsValid method of PhoneAttribute
public String Home { get; set; }
[DataType(DataType.PhoneNumber)] // <- does NOT execute IsValid method of PhoneAttribute
public String Mobile { get; set; }
[EmailAddress] // <- executes the IsValid method of EmailAddressAttribute
public String Email { get; set; }
[DataType(DataType.Currency)] // <- does the Currency formatting
public decimal Price { get; set; }
[DataType(DataType.Date)] // <- does the Date formatting
public DateTime ReleaseDate { get; set; }
[DataType(DataType.Text)] // <- does NOT add any validation/formatting
public string Name { get; set;}
/*
* this is the only scenario that I can think of, for using: [DataType(DataType.Text)]
*/
[DataType(DataType.Text)]
public object someKey { get; set;}
}
再次,根据我的理解,添加[DataType(DataType.Text)]
to string
,
不会增加任何价值,最好不要使用它,以保持代码更小、更干净、更容易理解......