Explain Common data annotation functions with examples.
Explain Common data annotation functions with examples.
268
20-Oct-2023
Updated on 22-Oct-2023
Aryan Kumar
22-Oct-2023Data annotations in ASP.NET Core are attributes that you can apply to model properties to define validation rules, control the display format, specify data types, and more. They play a crucial role in both validating user input and controlling how data is displayed in your application. Here are some common data annotations along with examples:
[Required] Data Annotation:
The [Required] attribute indicates that a property must have a non-null value.
[StringLength] Data Annotation:
The [StringLength] attribute specifies the minimum and maximum length of a string property.
[Range] Data Annotation:
The [Range] attribute is used to validate that a numeric property falls within a specified range.
[RegularExpression] Data Annotation:
The [RegularExpression] attribute enforces that a string property matches a specific regular expression pattern.
[EmailAddress] Data Annotation:
The [EmailAddress] attribute validates that a string property contains a valid email address.
[Url] Data Annotation:
The [Url] attribute ensures that a string property contains a valid URL.
[Compare] Data Annotation:
The [Compare] attribute checks if two properties have the same value. It's commonly used for confirming passwords.
[Display] Data Annotation:
The [Display] attribute specifies the display name for a property and can be used to customize how the property's name appears in views.
[DataType] Data Annotation:
The [DataType] attribute defines the data type of a property, which affects how it's displayed in views.
[Key] Data Annotation:
The [Key] attribute indicates that a property is the primary key in the database.
These are just a few examples of common data annotations in ASP.NET Core. They help ensure data integrity, validate user input, and control how data is presented in your application, ultimately improving the user experience and data quality.