0% found this document useful (0 votes)
44 views

Validation

This document discusses validation in ASP.NET MVC using unobtrusive JavaScript and data annotations. It covers implementing validation in the edit view of an MVC application by applying data annotation attributes to model properties, creating GET and POST edit action methods, and using validation tag helpers like ValidationSummary and ValidationMessageFor to display error messages. Remote validation and custom validation are also briefly discussed.

Uploaded by

Ahmed Shams
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Validation

This document discusses validation in ASP.NET MVC using unobtrusive JavaScript and data annotations. It covers implementing validation in the edit view of an MVC application by applying data annotation attributes to model properties, creating GET and POST edit action methods, and using validation tag helpers like ValidationSummary and ValidationMessageFor to display error messages. Remote validation and custom validation are also briefly discussed.

Uploaded by

Ahmed Shams
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

MVC

Christen Zarif Foad


OutLine
• Validation
VALIDATION
Unobtrusive javascript
• What is Unobtrusive Javascript?
– Is a JavaScript that is separated from the web site’s html
markup.
• There are several benefits of using Unobtrusive
Javascript
– Separation of Concems: i.e the HTML mark-up is now
clean without any traces of javascript .page load time is
faster
– It is also easy to update the code : as all th e Javascript
logic is present in a separate file
– We also get, better cache support: as all our Javascript is
now present in separate file , it can be cached and accessed
much faster
Unobtrusive Validation (Con.)
Edit View
Data Validation
• In this Edit form implement data validation, which will
display validation messages on the click of Save button ,
if Student Name or Age is blank.
• ASP.NET MVC uses DataAnnotations attributes for
validation.
• DataAnnotations attributes can be applied to the
properties of the model class to indicate the kind of value
the property will hold.
• You can apply multiple DataAnnotations validation
attributes to a single property if required.
• Each validation attribute assign to default message error.
Validation
• The following validation attributes available by default
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
Validation
• The following validation attributes available by default
Attribute Description
ValidateNever indicates that a property or parameter should be excluded from
validation
Compare Validates that two properties in a model match
Url Validates that the property has a URL format.
Remote Validates input on the client by calling an action method on the
server
Implement validation in edit view

• Step 1: First of all, apply DataAnnotation attribute on the


properties of Student model class.
• We want to validate
1. StudentName and Age is not blank.
2. Age should be between 5 and 50.
• the MVC framework will automatically display the default
error message, if the user tries to save the Edit form without
entering the Student Name,the same with Range attribute.

Model View
Implement validation (Con.)

• Step 2: Create the GET and POST Edit Action


method.
The GET action method
will render Edit view to
edit the selected student

The POST Edit method


will save edited student.

ModelState.IsValid:
determines that whether
submitted values satisfy
All the DataAnnotation
Validation attributes applied to model properties.
ModelState
• Model state represents errors that come from two
subsystems: model binding and model validation.
• Errors that originate from model binding are
generally data conversion errors.
– For example, an "x" is entered in an integer field.
• Model validation occurs after model binding and
reports errors where data doesn't conform to business
rules.
– For example, a 0 is entered in a field that expects a rating
between 1 and 5.
Implement Validation (Con.)

• Step 3 : in view used tag helper


• There are two Validation Tag Helpers.
– The Validation Message Tag Helper (which displays a
validation message for a single property on your model),
– The Validation Summary Tag Helper (which displays a
summary of validation errors).
Implement Validation (Con.)

• Step 3 : in view used tag helper


– The Input Tag Helper adds HTML5 client side validation
attributes to input elements based on data annotation
attributes on your model classes.

– Validation is also performed on the server.

– The Validation Tag Helper displays these error messages


when a validation error occurs.
Validation Summary Tag Helper
• Targets <div> elements with the asp-validation-
summary attribute
• The asp-validation-summary attribute value can be any of
the following:
Implement Validation (Con.)

• Step 3 : in view used


– 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.
– Or you can used scaffolding to create edit view using
template with validation
ValidationMessageFor
• The Html.ValidationMessageFor() is a strongly typed
extension method.
• It displays a validation message if an error exists for the
specified field in the ModelStateDictionary object.
• Method Signature :

• Method Parameters:
– The first Parameters :is a lambda expression to specify a
property for which we want to show the error message.
– The second parameter is for custom error message
– The third parameter is for html attributes like css, style etc
ValidationMessageFor (Con.)

• This method will only display an error if you have


configured DataAnnotations attribute to the specifed
property in the model class.

Model

View
ValidationMessageFor (Con.)
• Custom Error Message
– You can display your own error message instead of
the default error message , using:
• DataAnnotations Attribute:
[Required(ErrorMessage="Please enter student name.")]
public string StudentName { get; set; }

• ValidationMessageFor() Method:
@Html.Editor("StudentName") <br />
@Html.ValidationMessageFor(m => m.StudentName,
"Please enter student name.", new { @class = "text-
danger" })
ValidationSummary
• The ValidationSummary helper
method generates an unordered
list (ul element) of validation
messages that are in the
ModelStateDictionary object

• Method Signature:
ValidationSummary (Con.)

• By default, ValidationSummary filters out field level


error messages. If you want to display field level
error messages as a summary then specify
excludePropertyErrors = false.

• To display error messages as a summary at the top.


• Please make sure that you don't have a
ValidationMessageFor method for each of the fields.
ValidationSummary (Con.)

• Display custom error messages:


– For example, we want to display a message if Student
Name already exists in the database

Add custom errors


into the ModelState

– The ValidationSummary method will automatically


display all the error messages added into ModelState.
Remote Validation
• Remote Validation used to check whether the content
enter in the input control is valid or not by sending an
ajax request to server side to check it.
• The RemoteAttribute works by
– making an AJAX call from the client to a controller action
with the value of the field being validated.
– The controller action then returns a JsonResult response
indicating validation success or failure.
Remote Validation (Con.)
Remote Attribute (Con.)
Custom Validation
Custom Validator
Validation
• How can we do validations in MVC?
1. Model: By using attributes which can be applied on
model properties
2. View :To display the validation error message we need to
use the ValidateMessageFor method which belongs to
the Html helper class.
3. Controller: using the ModelState.IsValid property and
accordingly we can take actions
• 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 by
add Unobtrusive validation script links
Data annotations for Database first
(model code auto-generated)
• If you want to use the validators with the classes
generated by the Entity Framework then you need to
create meta data classes. You apply the validators to
the meta data class instead of applying the validators
to the actual class.
• Using [ModelMetadataType (typeof(ClassName))]

You might also like