- RequiredAttribute
- Range Attribute
- EmailAddressAttribute
- MinLengthAttribute
- MaxLengthAttribute
Required AttributeThe Required Attribute forces the required field validation for the specified data field.
Example
- [Required(ErrorMessage = "Please enter Name)]
- public string Name{ get; set; }
The Error message property is used to get/set the error message.
Range AttributeThe 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; }
EmailAddressAttributeThe 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 Expression AttributeRegular 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 ")]
Used for checking the field to have only numbers and min of 8 digits and max of 11 digits.
- [RegularExpression(@"[0-9]{0,}\.[0-9]{2}", ErrorMessage = "error Message")]
Used for checking the field to have only numbers with 2 decimal places.
- [RegularExpression(@"^(?!00000)[0-9]{5,5}$", ErrorMessage = "error Message")]
Used for validation Zip code. The Zip code should contain 5 digits and should not be 00000.
- [RegularExpression(@"^(\d{4})$", ErrorMessage = "error Message")]
The field should contain 4 digit numbers. Used for limiting the characters and allowing only numbers.
- [RegularExpression(@"^(\d{5,9})$", ErrorMessage = "error Message")]
The field should contain a minimum of 5 digit numbers and a maximum of 9 digit numbers.
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,}))$"
Used while validating the Zip codes. Also the number should not start with “0”.
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 AnnotaionsWhen 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" />
The following scripts should be added to the view page to enable Unobtrusive Client-side Validation via data Annotations.
- <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