Data Validation in ASP.NET MVC
In this article, we will learn how to
implement data validations in the ASP.NET MVC application.
In our previous article, we
have created an application that performs Create, Edit, Delete and Details operations
that generate views for each of the operations.
We will create new class called Blog and
will implement data validation in the class properties, which will display
validation messages on the click of Save button without data, as shown below in
the image below.
In the above image, we created a class named Blog with
data validation through data Annotation.
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 maximum
length for string field
|
||
Range
|
Defines minimum and
maximum value for a numeric field
|
||
RegularExpression
|
Speicifies the field
value must match with speicified Regular expression
|
||
|
Specifies that the
specified field is a credit card number
|
||
CustomValidation
|
Specifies 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
|
Sepcifies minimum
length for a string field
|
||
Phone
|
Specifies that the
field is a phone number using regular
expression for phone number
|
Implementing Validation to our Blog Class
Apply DataAnnotation attributes to the properties of
our Blog class as shown below
Here, we have made the Title property of the blog
class as compulsory by decorating it with Required attribute with error to be
displayed in case of irregularities.
The DatePosted property is decorated with two
attributes to make it compulsory and display in Calendar Date picker as shown
below
Save the project and create a controller with scaffolding
to generate the Create and Edit methods and View pages as shown below
Run the application and see that data validation is
properly enforced by the system as can be seen below
The view page provides the ValidationMessage HTML helper
method for error messages display as can be seen below
Thank you
Nice one
ReplyDeleteNice one
ReplyDelete