Data Annotations in ASP.NET

Data annotations are frequently used to regulate how model classes behave in relation to views, databases, and validation procedures.

Data Annotations in ASP.NET
Data annotations, Validations, Asp.Net, Programming - thetechfoyer, thetechfoyer.com

This Article helps to understand the concept of Data Annotations in ASP.NET

Our model properties can have Attributes (classes) applied to them called Data Annotations, which tell them how to behave in different scenarios.



Validation Attributes /Data Annotations:
[Required]: Mark property as a required field.


[StringLength(maxLength, MinimumLength = minLength)]: Specify the maximum and optional minimum length of for a string field.

[StringLength(150, ErrorMessage = "Last Name Should not Exceed 150 Characters.")]
public string LastName { get; set; }


[Required(ErrorMessage = "Last Name is Required.")]


[Range(min, max)]: Specifies the minimum and maximum value for a Numeric property.


[EmailAddress]: Validates that the property has an a valid email address.

[EmailAddress(ErrorMessage = "Invalid Email Address.")]
public string Email { get; set; }


[RegularExpression(pattern)]: Validates a property against a regular expression.


[Compare(“OtherProperty”)]: Validates that the property value matches another property’s value.

[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Passwords Do Not Match.")]
[Display(Name = "Confirm Password")]
public string ConfirmPassword { get; set; }



Formatting Attributes:
[DataType(DataType.Date)]: Validates that the property has an a valid date.

[DataType(DataType.Password)]
[StringLength(10, MinimumLength = 5, ErrorMessage = "Password Must Be Between 5 and 10 Characters.")]
public string Password { get; set; }


[DisplayFormat(DataFormatString = “{0:yyyy-MM-dd}”, ApplyFormatInEditMode = true)]: Impose a custom formatting for a property.



Display Attributes:
[Display(Name = “Display Name”)]: Specifies the display name for a property.

[Display(Name = "Last Name")]
public string LastName { get; set; }


[HiddenInput(DisplayValue = false)]: Mark a property as a hidden input element.

[DisplayOrder(order)]: Used to specify the order in which fields are displayed.



Database-Related Attributes (Work only With Entity Framework Core):
[Key]: Indicates that a property is a primary key.

[Key]
public int Id { get; set; }


[ForeignKey(“RelatedEntity”)]: Indicates that a property is a foreign key.

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]: Specifies how the database generates values for a primary key.

[Column(“ColumnNameInDb”)]: Specifies a different column name in the database than the property name in the model.



Misc Attributes:
[ReadOnly(true)]: Mark a property as read-only and non-editable.

Data Annotations in ASP.NET Core MVC Indicates that scaffolding mechanisms should ignore a property.