Friday, December 14, 2018

Validation in MVC

DataAnnotations
ASP.NET MVC uses DataAnnotations attributes to implement validations. DataAnnotations includes built-in validation attributes for different validation rules, which can be applied to the properties of model class. ASP.NET MVC framework will automatically enforce these validation rules and display validation messages in the view.


The DataAnnotations attributes included in System.ComponentModel.DataAnnotations namespace. The following table lists DataAnnotations validation attributes.

Attribute Description
Required Indicates that the property is a required field
StringLength Defines a maximum length for string field
Range Defines a maximum and minimum value for a numeric field
RegularExpression Specifies that the field value must match with specified Regular Expression
CreditCard Specifies that the specified field is a credit card number
CustomValidation Specified custom validation method to validate the field
EmailAddress Validates with email address format
FileExtension Validates with file extension
MaxLength Specifies maximum length for a string field
MinLength Specifies minimum length for a string field
Phone Specifies that the field is a phone number using regular expression for phone numbers

Use ValidationSummary to display all the error messages in the view.
Use ValidationMessageFor or ValidationMessage helper method to display field level error messages in the view.
Check whether the model is valid before updating in the action method using ModelState.IsValid.
Enable client side validation to display error messages without postback effect in the browser.

http://www.tutorialsteacher.com/mvc/implement-validation-in-asp.net-mvc

No comments:

Followers

Link