Data Annotation

Data Annotation Validator Attributes

Specify the datatype of a property

Syntax

 

[DataType(DataType.Text)]

specifies the display name for a property.

Syntax

 

[Display(Name="Student Name")]

specify the display format for a property like a different format for a Date property.

Syntax

 

[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]

Specify a property as required.

Syntax

 

[Required(ErrorMessage="Please enter name"),MaxLength(30)]

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.")]

validates the value of a property within a specified range of values.

Syntax

 

[Range(100,500,ErrorMessage="Please enter correct value")]

specifies the min and max length for a string property.

Syntax

 

[StringLength(30,ErrorMessage="Do not enter more than 30 characters")]

specifies the max length for a string property.

Syntax

 

[MaxLength(3)]

Specify fields to include or exclude when adding parameter or form values to model properties.

Syntax

 

[Bind(Exclude = "StudentID")]

specifies fields for hiding from editor forms.

How to use Data Annotation Validators




How to use Data Annotation Validators


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.

[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.

[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.

[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.

[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.

[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.

[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.

[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.

[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.

[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.

[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.

[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.

[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.

[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.

[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.

[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.

[StringLength(100, MinimumLength = 3, ErrorMessage = "Name must be between 5 and 10 characters")]

public string Name { get; set; }