Disclaimer: This is just my understanding from reading the source code (feel free to correct me)
(DataTypeAttribute) is a ValidationAttribute (derived from ValidationAttribute) and you need to pass it an Enum (which is also called DataType).
Validation Attributes need to override IsValid method, which is executed on model binding, and need to determine if the value is valid or not. This is how a custom validator would look like:
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...");
}
}
}
Now, getting back to DataTypeAttribue (which is a validation attribute), you need to pass it 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
}
From what I can see, all that DataTypeAttribtue does, is to add some formatting for DataType.Date, DataType.Time and DataType.Currency... (also set the _dataTypeStrings)
Further more, you have validation attributes like EmailAddressAttribute, PhoneAttribute, UrlAttribute, etc which are derived from DataTypeAttribute and do extra validation for these specific types:
Now this is how you can use these validation attributes:
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;}
}
Again, from what I can understand, adding [DataType(DataType.Text)] to string,
does not add any value, and is better not to use it to keep the code smaller, cleaner and easier to understand...