Data Annotation
Data Annotation Validator Attributes
DataType
Specify the datatype of a property
Syntax
Â
[DataType(DataType.Text)]
DisplayName
specifies the display name for a property.
Syntax
Â
[Display(Name="Student Name")]
DisplayFormat
specify the display format for a property like a different format for a Date property.
Syntax
Â
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
Required
Specify a property as required.
Syntax
Â
[Required(ErrorMessage="Please enter name"),MaxLength(30)]
Regular expression
validates the value of a property by a specified regular expression pattern.
Syntax
Â
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid.")]
Range
validates the value of a property within a specified range of values.
Syntax
Â
[Range(100,500,ErrorMessage="Please enter correct value")]
StringLength
specifies the min and max length for a string property.
Syntax
Â
[StringLength(30,ErrorMessage="Do not enter more than 30 characters")]
MaxLength
specifies the max length for a string property.
Syntax
Â
[MaxLength(3)]
Bind
Specify fields to include or exclude when adding parameter or form values to model properties.
Syntax
Â
[Bind(Exclude = "StudentID")]
ScaffoldColumn
specifies fields for hiding from editor forms.
How to use Data Annotation Validators
How to use Data Annotation Validators
Add Required Assembly
You need the necessary assembly referenced in your project to use Data Annotation validators. The System.ComponentModel.DataAnnotations namespace contains the validation attributes you'll use.Apply Validation Attributes to Model Properties
Decorate your model properties with Data Annotation validation attributes to specify validation rules. Some of the validation attributes include [Required], [StringLength], [Range], [EmailAddress], [RegularExpression], etc.
Example
using System.ComponentModel.DataAnnotations;
public class MyModel
{
    [Required(ErrorMessage = "The Name field is required.")]
    public string Name { get; set; }
    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
    public string Description { get; set; }
    [Range(18, 100, ErrorMessage = "The Age must be between {1} and {2}.")]
    public int Age { get; set; }
    [EmailAddress(ErrorMessage = "Invalid email address.")]
    public string Email { get; set; }
    [RegularExpression(@"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid ZIP code.")]
    public string ZipCode { get; set; }
}
0. [ValidateNever]
1. `[Required]`
The [Required] annotation ensures that a property cannot be null.
public class Person
{
          [Required]
          public string FirstName { get; set; }
}
Â
Â
2. `[StringLength]`
Defines the maximum and minimum length of a string property.
public class Product
{
          [StringLength(50, MinimumLength = 3)]
          public string Name { get; set; }
}
Â
Â
3. `[Range]`
Restricts a property to a specified numeric range.
public class Temperature
{
          [Range(-40, 100)]
          public int Celsius { get; set; }
}
Â
Â
4. `[RegularExpression]`
Validates a property against a regular expression pattern.
public class Email
{
          [RegularExpression(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$")]
          public string Address { get; set; }
}
Â
Â
5. `[Compare]`
Compares the values of two properties for equality.
public class User
{
          public string Password { get; set; }
Â
          [Compare("Password")]
          public string ConfirmPassword { get; set; }
}
Â
Â
6. `[EmailAddress]`
Ensures that a string property contains a valid email address.
public class Contact
{
          [EmailAddress]
          public string Email { get; set; }
}
Â
Â
7. `[Phone]`
Validates a string property as a phone number.
public class Contact
{
          [Phone]
          public string PhoneNumber { get; set; }
}
Â
Â
8. `[Url]`
Check if a string property contains a valid URL.
public class Website
{
          [Url]
          public string URL { get; set; }
}
Â
Â
9. `[CreditCard]`
Ensures a string property contains a valid credit card number.
public class Payment
{
          [CreditCard]
          public string CardNumber { get; set; }
}
Â
Â
10. `[MaxLength]`
Specifies the maximum length of a string property.
public class Tweet
{
          [MaxLength(280)]
          public string Text { get; set; }
}
Â
Â
11. `[MinLength]`
Sets the minimum length for a string property.
public class Password
{
          [MinLength(8)]
          public string Value { get; set; }
}
Â
Â
12. `[DataType]`
Specifies the data type of a property.
public class Person
{
          [DataType(DataType.Date)]
          public DateTime BirthDate { get; set; }
}
Â
Â
13. `[Display]`
Customizes the display name for a property.
public class Product
{
          [Display(Name = "Product Name")]
          public string Name { get; set; }
}
Â
Â
14. `[ScaffoldColumn]`
Hides a property from a scaffolding in ASP.NET MVC.
public class Employee
{
          [ScaffoldColumn(false)]
          public int EmployeeID { get; set; }
}
Â
Â
15. `[ScaffoldTable]`
Specifies the table name for an Entity Framework Entity.
[ScaffoldTable("tbl_Product")]
public class Product
{
          public string Name { get; set; }
}
Â
Â
16. `[Editable]`
Determines whether a property is editable in MVC.
[Editable(false)]
public class UserProfile
{
          public string FirstName { get; set; }
}
Â
Â
17. `[Key]`
Marks a property as the primary key for an Entity Framework Entity.
public class Customer
{
          [Key]
          public int CustomerID { get; set; }
}
Â
Â
18. `[ForeignKey]`
Defines a foreign key relationship in Entity Framework.
public class Order
{
          public int CustomerID { get; set; }
Â
          [ForeignKey("CustomerID")]
          public Customer Customer { get; set; }
}
Â
Â
19. `[Table]`
Specifies the table name for an Entity Framework entity.
[Table("Orders")]
public class Order
{
          public string OrderName { get; set; }
}
Â
Â
20. `[Column]`
Defines the column name for a property in Entity Framework.
public class User
{
          [Column("Full_Name")]
          public string FullName { get; set; }
}
Â
Â
21. `[ConcurrencyCheck]`
Indicates that a property should be included in optimistic concurrency checks.
public class Product
{
          [ConcurrencyCheck]
          public int UnitsInStock { get; set; }
}
Â
Â
22. `[Timestamp]`
Specifies that a property represents a database-generated timestamp.
public class Product
{
          [Timestamp]
          public byte[] RowVersion { get; set; }
}
Â
Â
23. `[DatabaseGenerated]`
Marks a property as database-generated.
public class Order
{
          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
          public int OrderID { get; set; }
}
Â
Â
24. `[NotMapped]`
Excludes a property from being mapped to the database.
public class User
{
          [NotMapped]
          public string FullName => $"{FirstName} {LastName}";
}
Â
Â
25. `[Bind]`
Specifies which properties should be included when binding data in an MVC action.
[Bind(Include = "FirstName, LastName, Email")]
public class UserProfile
{
          public string FirstName { get; set; }
          public string LastName { get; set; }
          public string Email { get; set; }
}
Data annotation attributes
15 Mar 202420 minutes to read
The DataForm component enables users to define the data annotation attributes available from the instance of System.ComponentModel.DataAnnotations.
Display attribute
The DisplayAttribute class is used to specify the display name for a property. The display name is used as the label for the corresponding editor in the DataForm component if label text is not specified for the form item.
Name property
The Name property is used to specify the display name for a property. The display name is used as the label for the corresponding editor in the DataForm component if label text is not specified for the form item.
C#
[Display(Name = "First Name")]
public string FirstName { get; set; }
Short name property
The ShortName property is used to specify the short display name for a property. The short display name is used as the label for the corresponding editor in the DataForm component if label text is not specified for the form item.
C#
[Display(ShortName = "First Name")]
public string FirstName { get; set; }
NOTE
DataForm gives priority to the ShortName property over the Name property of DisplayAttribute and LabelText property of the FormItem.
Prompt property
The Prompt property is used to specify the prompt for a property. The prompt is used as the placeholder for the corresponding editor in the DataForm component.
C#
[Display(Prompt = "Enter your first name")]
public string FirstName { get; set; }
Auto generate field property
The AutoGenerateField property is used to specify whether the property should be automatically generated as a field in the DataForm component.
C#
[Display(AutoGenerateField = false)]
public string ID { get; set; }
Validation attributes
The DataForm component supports the following validation attributes from the System.ComponentModel.DataAnnotations namespace.
Required attribute
The RequiredAttribute class is used to specify that a property is required. The DataForm component displays an error message if the property is empty.
C#
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
Range attribute
The RangeAttribute class is used to specify the numeric range constraints for the value of a property. The DataForm component displays an error message if the property value is not within the specified range.
C#
[Range(0, 100, ErrorMessage = "Age must be between 0 and 100")]
public int Age { get; set; }
Regular expression attribute
The RegularExpressionAttribute class is used to specify that a property value must match a specified regular expression. The DataForm component displays an error message if the property value does not match the specified regular expression.
C#
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Name must contain only alphabets")]
public string Name { get; set; }
String length Attribute
The StringLengthAttribute class is used to specify the minimum and maximum length constraints for the value of a property. The DataForm component displays an error message if the property value is not within the specified length constraints.
C#
[StringLength(100, MinimumLength = 3, ErrorMessage = "Name must be between 5 and 10 characters")]
 public string Name { get; set; }
Minimum length Attribute
The MinLengthAttribute class is used to specify the minimum length constraints for the value of a property. The DataForm component displays an error message if the property value is not within the specified length constraints.
C#
[MinLength(3, ErrorMessage = "Name must be at least 3 characters")]
public string Name { get; set; }
Maximum length Attribute
The MaxLengthAttribute class is used to specify the maximum length constraints for the value of a property. The DataForm component displays an error message if the property value is not within the specified length constraints.
C#
[MaxLength(10, ErrorMessage = "Name must be at most 10 characters")]
public string Name { get; set; }
Phone number attribute
The PhoneAttribute class is used to specify that a property value must match a specified phone number pattern. The DataForm component displays an error message if the property value does not match the specified phone number pattern.
C#
[Phone(ErrorMessage = "Phone number is not valid")]
public string PhoneNumber { get; set; }
Email address attribute
The EmailAddressAttribute class is used to specify that a property value must match a specified email address pattern. The DataForm component displays an error message if the property value does not match the specified email address pattern.
C#
[EmailAddress(ErrorMessage = "Email address is not valid")]
public string Email { get; set; }
URL attribute
The UrlAttribute class is used to specify that a property value must match a specified URL pattern. The DataForm component displays an error message if the property value does not match the specified URL pattern.
C#
[Url(ErrorMessage = "URL is not valid")]
public string Url { get; set; }
Enum data type attribute
The EnumDataTypeAttribute class is used to specify that a property value must be a member of the specified enumeration. The DataForm component displays an error message if the property value is not a member of the specified enumeration.
C#
[EnumDataType(typeof(Gender), ErrorMessage = "Please enter a valid gender")]
 public string Gender { get; set; }
Compare attribute
The CompareAttribute class is used to specify that a property value must match the value of another property in the same class. The DataForm component displays an error message if the property value does not match the value of the other property.
C#
[Compare("Password", ErrorMessage = "Passwords do not match")]
public string ConfirmPassword { get; set; }
String length attribute
The StringLengthAttribute class is used to specify the minimum and maximum length constraints for the value of a property. The DataForm component displays an error message if the property value is not within the specified length constraints.Additionally editor component will not allow to enter more than the specified length.
C#
[StringLength(100, MinimumLength = 3, ErrorMessage = "Name must be between 5 and 10 characters")]
public string Name { get; set; }