Introduction
Data Annotations is a library in the .NET Framework that helps in validation. The developer doesn't need to create the logic for the validation since the validation can be done by specifying the data annotation attributes that forces the data validation rules.
Namespace
The namespace System.ComponentModel.DataAnnotations provides the attribute classes for validations.
Attribute Classes
There are more than 30 attribute classes in the System.ComponentModel.DataAnnotations namespace. We will discuss some of the most commonly used attributes.
- RequiredAttribute
- Range Attribute
- EmailAddressAttribute
- MinLengthAttribute
- MaxLengthAttribute
The Required Attribute forces the required field validation for the specified data field.
Example
- [Required(ErrorMessage = "Please enter Name)]
- public string Name{ get; set; }
Range Attribute
The Range attribute forces the range validation for the data field.
Example
- [Range(1.00, 100.00,ErrorMessage="Please enter a Amount between 1.00 and 100.00" )]
- public decimal? Amount { get; set; }
The Email address attribute forces the validation and checks to ensure that the field has a valid email ID.
Example
- [EmailAddress(ErrorMessage = "Please enter a valid Email address")]
- public string email { get; set; }
Regular expressions can be added to a data field. The added regular expression will be forced for validation.
Some of most commonly used snippets for validation
- [RegularExpression(@"^[0-9]{8,11}$", ErrorMessage = "error Message ")]
- [RegularExpression(@"[0-9]{0,}\.[0-9]{2}", ErrorMessage = "error Message")]
- [RegularExpression(@"^(?!00000)[0-9]{5,5}$", ErrorMessage = "error Message")]
- [RegularExpression(@"^(\d{4})$", ErrorMessage = "error Message")]
- [RegularExpression(@"^(\d{5,9})$", ErrorMessage = "error Message")]
Regex for validating Email.
- @"^(([^<>()[\]\\.,;:\s@""]+(\.[^<>()[\]\\.,;:\s@""]+)*)|("".+""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"
- @"^(?!0+$)[0-9]{5,5}$"
MinLengthAttribute
Validates the minimum length of the data field (String/Array). It will not work for int types.
MaxLengthAttribute
Validates the maximum length of the data field (String/Array). It will not work for int types.
Enabling Unobtrusive Client-side Validation via data Annotaions
When we include the following changes in the config file, the client-side validation will be done based on the data annotation rules that we have defined in the model.
- <add key="ClientValidationEnabled" value="true" />
- lt;add key="UnobtrusiveJavaScriptEnabled" value="true" />
- <script src="~/Scripts/jquery-2.1.1.js"></script>
- <script src="~/Scripts/jquery.validate.min.js"></script>
- <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script
0 Comments