SlideShare una empresa de Scribd logo
GTC
How to validate data
By : Eng. Mahmoud Hassouna
Email : M.hassuna2@gmail.com
GTC
 Perspective
• The goal of this chapter is to teach you how to validate the data that a
user
• inputs into an ASP.NET MVC app. Now, if this chapter has worked, you
should
• be able to use client-side and server-side code to validate data. This
includes
• using the data attributes that are provided by MVC as well as creating
your own
• custom data attributes. As usual, there’s always more to learn. Still, this
chapter
• should give you a good foundation for working with data validation.
 Terms
• data attribute
• property-level validation
• class-level validation
• remote validation
GTC
 Summary
• You specify the validation to be applied to a model class by
decorating
its properties with data attributes.
• Code that validates a property of a class is called property-level
validation. Code that validates the entire class instead of
individual
properties is called class-level validation. Class-level validation
only
runs if all the property-level validation has passed.
• Remote validation allows you to write code on the server that’s
called by
the client without reloading the whole page
GTC
 How data validation works in MVC
1. The default data validation provided by model binding
The action method accepts a Movie object named movie. When the view posts to this
method, MVC binds the values it receives from the view to the Movie object. If MVC can’t bind
a value, it adds a validation message to the Model State property of the Controller class. That’s
why this action method starts by checking whether the Model State is valid. If it is, no errors
occurred during model binding. In this case, the action method redirects to the page that lists
the movies. Otherwise, if errors occurred during model binding, the action method returns the
original view. In addition, it passes the Movie object parameter back to the view. This returns
the values that the user posted. As a result, the view can redisplay them to the user. Also, since
the Model State property contains validation messages, the validation summary tag displays
those messages in red. In this figure, the Movie class doesn’t decorate its properties with any
data attributes. As a result, the code in this figure doesn’t check for required fields or check
whether a value is in range as described in the next figure. However, as described in the
previous chapter, when MVC performs model binding, it casts the data posted by the view to
the parameter type specified by the action method. If this data conversion fails, MVC adds a
message to the Model State property. As a result, this code notifies the user about data
conversions that fail, even though there are no data attributes in the model. For example, the
screen in this figure shows the view after the user enters a string of “four” in the Rating field.
Since MVC can’t cast that string to the int type, the data conversion fails and MVC adds a
message to the Model State property and sets its Is Valid property to false. As a result, when the
action method checks the Is Valid property, its value is false. This causes the view to display the
validation messages and the values the user entered. You can also avoid this error by removing
the type=“text” attribute from the element. Then, the asp-for tag helper will generate a number
field instead of a text field since the Rating property has a data type of int.
GTC
 How it looks in the browser when the rating
can’t be cast to an int.
Description
• When you use model binding and MVC can’t cast an HTTP request value to the
data type specified by the action method parameter, it adds an error message to the
Model State property of the Controller class.
GTC
 2.How to use data attributes for validation
The two-argument Range attribute accepts int or double values that specify
the minimum and maximum values of the range. However, the three-argument
Range attribute also accepts a type argument that indicates the type of the
values to compare. For example, the next figure shows how to use this type
argument to compare Date Time values. When you use the type argument, the
minimum and maximum values must be strings. The String Length attribute
checks that the value of a string property doesn’t exceed a specified number
of characters. This attribute accepts an int value that specifies the maximum
number of characters. The Regular Expression attribute checks that the value of
a property matches a regular expression (regex) pattern. It accepts a string
value that’s the pattern to match. Regular expression patterns are beyond the
scope of this book, but you can find many good resources and regex libraries
online. The Compare attribute checks that the value of the property matches
the value of another property in the model. It accepts a string value that
contains the name of the other property. The Display attribute doesn’t check
any values. Instead, it specifies how the name of the property should be
displayed to the user. That includes not only how it’s displayed in a validation
message, but how it’s displayed in a label that’s bound to the property.
GTC
GTC
3. A Registration page with data validation
The DOB property has a Range attribute that includes a type argument to indicate that the
range is of the Date Time type. Then, it passes two string arguments that indicate the minimum
and maximum dates for the range. This code sets the maximum value to a date that’s in the
distant future to make sure the current date is always before the maximum value. Later, this
chapter presents some techniques for using code to compare a date to the current date.
Note that the DOB property is of the Date Time? type, not the Date Time type. This is necessary
for the Required attribute to work properly. The Password property has a String Length attribute
that only allows string values of 25 characters or less. This attribute doesn’t include a custom
validation message because the default message is adequate. In addition, text fields and
password fields often prevent the error message from being displayed by not allowing the user
to enter more than the specified number of characters. The Password property also has a
Compare attribute that tells MVC to check that the value of this property matches the value
of the Confirm Password property. This attribute doesn’t include a custom validation message.
That’s because the default message for the Compare attribute is adequate here. The Confirm
Password property has a Display attribute that adds a space to the property name. As a result,
this property displays as “Confirm Password” in the default validation message of the
Compare attribute that decorates the Password property. The second code example presents
the validation and tags in a strongly-typed view that posts a Customer object to an action
method. Here, the tags for the passwords are of the password type. This displays bullets for the
characters.
GTC
GTC
 How to control the user experience
So far, you’ve learned how to use Bootstrap CSS classes to
make messages in a validation summary tag display in red. In
addition, you’ve learned how to add your own validation
messages to a data attribute. In the next few figures, you’ll learn
more skills for controlling how MVC displays validation messages
to the user.
GTC
 How to format validation messages with CSS
This HTML includes a data-val attribute with a value of “true”. In addition, it includes
several data-val-* attributes that contain information MVC emits for the Required
and Regular Expression attributes that decorate the Name property. When data
validation fails, MVC also assigns a CSS class named input-validation-error to the tag
as shown in the second example. The tags that use the asp-validation-summary tag
helper work similarly. For instance, the third example shows that MVC adds a data-
valmsgsummary attribute to the tag. In addition, if validation succeeds, it assigns the
tag to a CSS class named validation-summary-valid. However, if validation fails, MVC
assigns the tag to a CSS class named validation summary-errors as shown by the
fourth example. You can define style rules for these CSS classes to control how these
tags appear to the user. For instance, the last example presents style rules for all
three CSS classes. For tags that have failed validation, the CSS adds a border that’s
the same color as the Bootstrap text-danger CSS class. In addition, it adds a
background color. The screen at the bottom of this figure shows how such an tag
appears on the page. The last two style rules are for validation summary tags. When
validation succeeds (or when the page first loads), the first style rule sets the display
to none. This hides the tag and prevents it from taking up any space on the page.
Then, if you want, you can include a generic message like this and it won’t be
displayed unless validation fails:
GTC
GTC
 How to check validation state and use code to
set validation messages
The Is Valid property returns false if there are any validation messages.
The Keys property is a collection that contains the names of the form
data parameters that were posted. And the Values property is a
collection that contains the values of those parameters. The second
table in this figure shows two of the methods of the
ModelStateDictionary class. The AddModelError() method adds a
validation message. It accepts two string values. The first argument
specifies the name of the property that’s associated with the
validation message. However, if you want to associate the message
with the overall model, you can pass an empty string to this
argument. The second argument specifies the validation message
itself. The GetValidationState() method returns the validation state of
the specified property.
GTC
Some of the properties of the
ModelStateDictionary class
Two of the methods of the
ModelStateDictionary class
Code that adds a
validation message
to the ModelState
property
GTC
 How to display model-level and property-
level validation messages
The code below the tables shows how to display model-level messages in one place
and property-level messages in another. This action method accepts a Customer
object as an argument. As usual, it uses the controller’s ModelState property to check
whether validation has succeeded. If not, the code adds another message and
associates it with the model. The view has a tag that uses the asp-validation-summary
tag helper. This time, though, the code sets the tag helper to “Model Only” rather than
“All”. This means that the tag only displays model-level messages like the one added
by the action method in this figure. Below the tag, the view includes the tags for the
form. Here, each tag is followed by a tag that uses the asp-validation-for tag helper.
This HTML sets the value of each tag helper to the same property name that’s bound
to the corresponding tag. This means that each tag displays the first property-level
message for the specified property. The screen at the bottom of the figure shows what
the browser displays when validation fails. Here, the page displays the model-level
message that notifies the user that the form contains errors above the form. Then, the
property-level messages that describe how to fix the invalid data for each entry
display to the right of each text box.
GTC
 An action method that
adds a model-level
validation message
 Part of a view that displays both
model-level and property-level
messages
GTC
 How to enable client-side validation
Second, if there’s custom validation on the server, such as the DOB check
shown in figure 11-5, validation can run twice. In other words, after the client
side validation passes, the form posts to the server, and the server-side
validation runs. This can lead to a process where the user gets validation
messages in two different steps, which some users might not like. Whenever
possible, it’s best to let your users know in one step everything they need to
do to fix their data entry. Third, not all of the MVC data attributes work
properly with the jQuery validation libraries. In particular, the Range attribute
doesn’t work well with dates. For example, in the screen at the bottom of this
figure, the user has entered a date of 1/1/1971, which is after 1/1/1900, but
the client-side validation is telling the user otherwise. In a case like this, you
need to use custom validation as shown later in this chapter. When working
with validation, keep in mind that client-side validation is not a substitute for
server-side validation. That’s because a user’s browser might have
JavaScript turned off, or a malicious user might tamper with the JavaScript.
As a result, you should think of client-side validation as a convenience for
your users. You should always validate user input on the server as well
GTC
 Some caveats to client-side validation
 It only works correctly with property-level validation, not model-level
validation.
 Any server-side validation doesn’t run until all client-side validation passes.
This can lead to a 2-step process that may annoy some users.
 Not all data annotations work properly on the client. In the example below,
for instance, the Range annotation for the DOB field isn’t working as it should.
GTC
 The jQuery libraries in the head section of a
Layout view
GTC
 How to customize server-side validation
1.How to create a custom data attribute
To create a custom data attribute, you code a class that inherits the Validation Attribute class
and overrides its Is Valid() method as shown by the PastDateAttribute class presented in this
figure. It’s a convention to include a suffix of Attribute at the end of the class name. However, you
don’t include that suffix when you decorate a model property. The Is Valid() method of the
PastDateAttribute class starts by checking whether the value it receives is a date. If so, it casts
that value to a Date Time object. Then, it checks whether the date is in the past. If so, the Is
Valid() method returns the Success field of the Validation Result class. If the date isn’t in the past,
the Is Valid() method returns a new Validation Result object that contains an error message. But
first, it builds the message to pass to the constructor of the Validation Result object. To do that, it
checks the Error Message property of the base class
GTC
 A constructor and a field of the
Validation Result class
 A custom data attribute that
checks if a date is in the past
GTC
 How to pass values to a custom data attribute
The Is Valid() method in this figure starts by making sure that the value it
receives is a date. If so, it casts this value to a Date Time object. After that, it
assigns the current date to a Date Time variable named now and declares
another Date Time variable named from. These from and now variables
define the range of valid dates. The code then uses the Is Past property to
calculate the from variable. If the date is in the past, the code creates a
new Date Time value for January 1 of the current year and assigns it to the
from variable. Then, this code subtracts the number of years in the
numYears variable. So, if the current year is 2020 and the value in numYears
is 25, the from date would be 1/1/1995. Conversely, if the date is in the
future, the code creates a new Date Time value for December 31 of the
current year and assigns it to the from variable. Then, this code adds the
number of years in the numYears variable. So, if the current year is 2020 and
the value in numYears is 25, the from date will be 12/31/2045
GTC
 A custom attribute that accept values via a
constructor and a property
GTC
 How to check multiple properties
The two custom data attributes you’ve seen so far only
check the value of the property they decorate. However, it’s
possible to create a data attribute that checks more than
one property in the model object. For instance, the
RequiredContactInfo data attribute at the top of figure 11-10
checks that a user has entered either a phone number or an
email address. To do that, the code in the Is Valid() method
uses the Object Instance property of the Validation Context
class to return the object that contains the properties being
checked. However, it returns it as the object type, so you
need to cast it to the correct type. In this example, the code
casts the object to the Customer type. To use an attribute
like this, you only need to decorate one of the properties it
validates with the attribute.
GTC
 A custom attribute that
checks more than one
property in a class
A custom validation
class that checks more
than one field
GTC
 A custom attribute that checks
more than one property in a class:-
 public class RequiredContactInfoAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object v,
ValidationContext c){
var cust = (Customer)c.ObjectInstance;
if (string.IsNullOrEmpty(cust.PhoneNumber) &&
string.IsNullOrEmpty(cust.EmailAddress))
{
string msg = base.ErrorMessage ?? "Enter phone number or email.";
return new ValidationResult(msg);
}
else {
return ValidationResult.Success;
}
}
}
GTC
 The single method of the IValidatableObject interface
 A constructor of the ValidationResult class
GTC
 How to add data attributes to the
generated HTML :-
 A method of the IClientModelValidator interface
GTC
The updated PastDate attribute with client-
side validation .
GTC
 Two constructors of the RemoteAttribute class
 A model property with a Remote attribute
GTC
 The CheckEmail() action method in the
Validation controller
 One property of the RemoteAttribute class
GTC
The Registration app with invalid data.
GTC
 The Customer class
GTC
 The RegistrationContext class
GTC
 Description
 The Customer class provides data validation by decorating its
properties with
attributes from the System.ComponentModel.DataAnnotations
namespace.
 The Customer class uses the Remote attribute to use server-side
code to check if the
email address entered by the user is already in the database.
120
 The Customer class uses a custom MinimumAge attribute to
check if the user is at
least 13 years old.
 The RegistrationContext class communicates with a database
named Registration.
To configure it, you must modify the Startup.cs and
appsettings.json files as
described in chapter 4.
GTC
 The MinimumAgeAttribute class.
GTC
 The Validation controller:
GTC
 The Register controller
GTC
 The static Check class
GTC
 The layout:-
GTC
Description
• The layout includes the jQuery library at the end
of the <body> tag, though you can
include it in the <head> tag instead if you
prefer.
• The layout calls the RenderSection() method. This
allows individual views to
add additional JavaScript files. It places this
statement after the <script> tag that
includes the jQuery library
GTC
 The Register/Index view
GTC
Description
The Register/Index view has a Razor section named
scripts that includes the jQuery
validation libraries and the minimum-age.js file. That
way, these JavaScript files are
only loaded for the Registration page, not for other
pages of the app that don’t need
them.
GTC
The end

Más contenido relacionado

La actualidad más candente

Murach: An introduction to web programming with ASP.NET Core MVC
Murach: An introduction to web programming with ASP.NET Core MVCMurach: An introduction to web programming with ASP.NET Core MVC
Murach: An introduction to web programming with ASP.NET Core MVC
MahmoudOHassouna
 
MVC Training Part 2
MVC Training Part 2MVC Training Part 2
MVC Training Part 2
Lee Englestone
 
Salesforce connector Example
Salesforce connector ExampleSalesforce connector Example
Salesforce connector Example
prudhvivreddy
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
Bagzzz
 
Less10 2 e_testermodule_9
Less10 2 e_testermodule_9Less10 2 e_testermodule_9
Less10 2 e_testermodule_9
Suresh Mishra
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
Vba
Vba Vba
FlexNet Delivery and FlexNet Operations On-Demand Tips & Tricks
FlexNet Delivery and FlexNet Operations On-Demand Tips & TricksFlexNet Delivery and FlexNet Operations On-Demand Tips & Tricks
FlexNet Delivery and FlexNet Operations On-Demand Tips & Tricks
Flexera
 
Mvc by asp.net development company in india - part 2
Mvc by asp.net development company in india  - part 2Mvc by asp.net development company in india  - part 2
Mvc by asp.net development company in india - part 2
iFour Institute - Sustainable Learning
 
jQuery plugins & JSON
jQuery plugins & JSONjQuery plugins & JSON
Gutmacher practical-coding-examples-for-sourcers-sc18 atl
Gutmacher practical-coding-examples-for-sourcers-sc18 atlGutmacher practical-coding-examples-for-sourcers-sc18 atl
Gutmacher practical-coding-examples-for-sourcers-sc18 atl
Glenn Gutmacher
 
Transforming Power Point Show with VBA
Transforming Power Point Show with VBATransforming Power Point Show with VBA
Transforming Power Point Show with VBA
DCPS
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
Lee Englestone
 
Oracle9i reports developer
Oracle9i reports developerOracle9i reports developer
Oracle9i reports developer
FITSFSd
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
Akhil Mittal
 
Forms With Ajax And Advanced Plugins
Forms With Ajax And Advanced PluginsForms With Ajax And Advanced Plugins
Forms With Ajax And Advanced Plugins
Manuel Lemos
 
E learning excel vba programming lesson 1
E learning excel vba programming  lesson 1E learning excel vba programming  lesson 1
E learning excel vba programming lesson 1
Vijay Perepa
 
Sqlite3 databases
Sqlite3 databasesSqlite3 databases
Sqlite3 databases
Mohamed Essam
 
Excel vba
Excel vbaExcel vba
Excel vba
Almeda Asuncion
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 

La actualidad más candente (20)

Murach: An introduction to web programming with ASP.NET Core MVC
Murach: An introduction to web programming with ASP.NET Core MVCMurach: An introduction to web programming with ASP.NET Core MVC
Murach: An introduction to web programming with ASP.NET Core MVC
 
MVC Training Part 2
MVC Training Part 2MVC Training Part 2
MVC Training Part 2
 
Salesforce connector Example
Salesforce connector ExampleSalesforce connector Example
Salesforce connector Example
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
 
Less10 2 e_testermodule_9
Less10 2 e_testermodule_9Less10 2 e_testermodule_9
Less10 2 e_testermodule_9
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Vba
Vba Vba
Vba
 
FlexNet Delivery and FlexNet Operations On-Demand Tips & Tricks
FlexNet Delivery and FlexNet Operations On-Demand Tips & TricksFlexNet Delivery and FlexNet Operations On-Demand Tips & Tricks
FlexNet Delivery and FlexNet Operations On-Demand Tips & Tricks
 
Mvc by asp.net development company in india - part 2
Mvc by asp.net development company in india  - part 2Mvc by asp.net development company in india  - part 2
Mvc by asp.net development company in india - part 2
 
jQuery plugins & JSON
jQuery plugins & JSONjQuery plugins & JSON
jQuery plugins & JSON
 
Gutmacher practical-coding-examples-for-sourcers-sc18 atl
Gutmacher practical-coding-examples-for-sourcers-sc18 atlGutmacher practical-coding-examples-for-sourcers-sc18 atl
Gutmacher practical-coding-examples-for-sourcers-sc18 atl
 
Transforming Power Point Show with VBA
Transforming Power Point Show with VBATransforming Power Point Show with VBA
Transforming Power Point Show with VBA
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
 
Oracle9i reports developer
Oracle9i reports developerOracle9i reports developer
Oracle9i reports developer
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
 
Forms With Ajax And Advanced Plugins
Forms With Ajax And Advanced PluginsForms With Ajax And Advanced Plugins
Forms With Ajax And Advanced Plugins
 
E learning excel vba programming lesson 1
E learning excel vba programming  lesson 1E learning excel vba programming  lesson 1
E learning excel vba programming lesson 1
 
Sqlite3 databases
Sqlite3 databasesSqlite3 databases
Sqlite3 databases
 
Excel vba
Excel vbaExcel vba
Excel vba
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 

Similar a Murach: How to validate data in asp.net core mvc

MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
ArthyR3
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
sonia merchant
 
R Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioR Tanenbaum .Net Portfolio
R Tanenbaum .Net Portfolio
Robert Tanenbaum
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
vrluckyin
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
Nisa Soomro
 
How to Build Dynamic Forms in Angular Directive with a Backend
How to Build Dynamic Forms in Angular Directive with a BackendHow to Build Dynamic Forms in Angular Directive with a Backend
How to Build Dynamic Forms in Angular Directive with a Backend
Backand Cohen
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
icubesystem
 
Forms with html5 (1)
Forms with html5 (1)Forms with html5 (1)
Forms with html5 (1)
Anada Kale
 
Forms with html5
Forms with html5Forms with html5
Forms with html5
Suvarna Pappu
 
html 5 new form attribute
html 5 new form attributehtml 5 new form attribute
html 5 new form attribute
Priyanka Rasal
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]
Mohamed Abdeen
 
Wheels
WheelsWheels
Wheels
guest9fd0a95
 
Learning .NET Attributes
Learning .NET AttributesLearning .NET Attributes
Learning .NET Attributes
Pooja Gaikwad
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributes
sonia merchant
 
ASP.NET 03 - Working With Web Server Controls
ASP.NET 03 - Working With Web Server ControlsASP.NET 03 - Working With Web Server Controls
ASP.NET 03 - Working With Web Server Controls
Randy Connolly
 
Fahri tugas cloud1
Fahri tugas cloud1Fahri tugas cloud1
Fahri tugas cloud1
FAHRIZAENURIPUTRA
 
Applying Code Customizations to Magento 2
Applying Code Customizations to Magento 2 Applying Code Customizations to Magento 2
Applying Code Customizations to Magento 2
Igor Miniailo
 
Chapter09
Chapter09Chapter09
Chapter09
Sreenivasan G
 
I am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdfI am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdf
mallik3000
 
Angular Framework ppt for beginners and advanced
Angular Framework ppt for beginners and advancedAngular Framework ppt for beginners and advanced
Angular Framework ppt for beginners and advanced
Preetha Ganapathi
 

Similar a Murach: How to validate data in asp.net core mvc (20)

MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
R Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioR Tanenbaum .Net Portfolio
R Tanenbaum .Net Portfolio
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
How to Build Dynamic Forms in Angular Directive with a Backend
How to Build Dynamic Forms in Angular Directive with a BackendHow to Build Dynamic Forms in Angular Directive with a Backend
How to Build Dynamic Forms in Angular Directive with a Backend
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
Forms with html5 (1)
Forms with html5 (1)Forms with html5 (1)
Forms with html5 (1)
 
Forms with html5
Forms with html5Forms with html5
Forms with html5
 
html 5 new form attribute
html 5 new form attributehtml 5 new form attribute
html 5 new form attribute
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]
 
Wheels
WheelsWheels
Wheels
 
Learning .NET Attributes
Learning .NET AttributesLearning .NET Attributes
Learning .NET Attributes
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributes
 
ASP.NET 03 - Working With Web Server Controls
ASP.NET 03 - Working With Web Server ControlsASP.NET 03 - Working With Web Server Controls
ASP.NET 03 - Working With Web Server Controls
 
Fahri tugas cloud1
Fahri tugas cloud1Fahri tugas cloud1
Fahri tugas cloud1
 
Applying Code Customizations to Magento 2
Applying Code Customizations to Magento 2 Applying Code Customizations to Magento 2
Applying Code Customizations to Magento 2
 
Chapter09
Chapter09Chapter09
Chapter09
 
I am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdfI am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdf
 
Angular Framework ppt for beginners and advanced
Angular Framework ppt for beginners and advancedAngular Framework ppt for beginners and advanced
Angular Framework ppt for beginners and advanced
 

Último

BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
สมใจ จันสุกสี
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 

Último (20)

BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 

Murach: How to validate data in asp.net core mvc

  • 1. GTC How to validate data By : Eng. Mahmoud Hassouna Email : M.hassuna2@gmail.com
  • 2. GTC  Perspective • The goal of this chapter is to teach you how to validate the data that a user • inputs into an ASP.NET MVC app. Now, if this chapter has worked, you should • be able to use client-side and server-side code to validate data. This includes • using the data attributes that are provided by MVC as well as creating your own • custom data attributes. As usual, there’s always more to learn. Still, this chapter • should give you a good foundation for working with data validation.  Terms • data attribute • property-level validation • class-level validation • remote validation
  • 3. GTC  Summary • You specify the validation to be applied to a model class by decorating its properties with data attributes. • Code that validates a property of a class is called property-level validation. Code that validates the entire class instead of individual properties is called class-level validation. Class-level validation only runs if all the property-level validation has passed. • Remote validation allows you to write code on the server that’s called by the client without reloading the whole page
  • 4. GTC  How data validation works in MVC 1. The default data validation provided by model binding The action method accepts a Movie object named movie. When the view posts to this method, MVC binds the values it receives from the view to the Movie object. If MVC can’t bind a value, it adds a validation message to the Model State property of the Controller class. That’s why this action method starts by checking whether the Model State is valid. If it is, no errors occurred during model binding. In this case, the action method redirects to the page that lists the movies. Otherwise, if errors occurred during model binding, the action method returns the original view. In addition, it passes the Movie object parameter back to the view. This returns the values that the user posted. As a result, the view can redisplay them to the user. Also, since the Model State property contains validation messages, the validation summary tag displays those messages in red. In this figure, the Movie class doesn’t decorate its properties with any data attributes. As a result, the code in this figure doesn’t check for required fields or check whether a value is in range as described in the next figure. However, as described in the previous chapter, when MVC performs model binding, it casts the data posted by the view to the parameter type specified by the action method. If this data conversion fails, MVC adds a message to the Model State property. As a result, this code notifies the user about data conversions that fail, even though there are no data attributes in the model. For example, the screen in this figure shows the view after the user enters a string of “four” in the Rating field. Since MVC can’t cast that string to the int type, the data conversion fails and MVC adds a message to the Model State property and sets its Is Valid property to false. As a result, when the action method checks the Is Valid property, its value is false. This causes the view to display the validation messages and the values the user entered. You can also avoid this error by removing the type=“text” attribute from the element. Then, the asp-for tag helper will generate a number field instead of a text field since the Rating property has a data type of int.
  • 5. GTC  How it looks in the browser when the rating can’t be cast to an int. Description • When you use model binding and MVC can’t cast an HTTP request value to the data type specified by the action method parameter, it adds an error message to the Model State property of the Controller class.
  • 6. GTC  2.How to use data attributes for validation The two-argument Range attribute accepts int or double values that specify the minimum and maximum values of the range. However, the three-argument Range attribute also accepts a type argument that indicates the type of the values to compare. For example, the next figure shows how to use this type argument to compare Date Time values. When you use the type argument, the minimum and maximum values must be strings. The String Length attribute checks that the value of a string property doesn’t exceed a specified number of characters. This attribute accepts an int value that specifies the maximum number of characters. The Regular Expression attribute checks that the value of a property matches a regular expression (regex) pattern. It accepts a string value that’s the pattern to match. Regular expression patterns are beyond the scope of this book, but you can find many good resources and regex libraries online. The Compare attribute checks that the value of the property matches the value of another property in the model. It accepts a string value that contains the name of the other property. The Display attribute doesn’t check any values. Instead, it specifies how the name of the property should be displayed to the user. That includes not only how it’s displayed in a validation message, but how it’s displayed in a label that’s bound to the property.
  • 7. GTC
  • 8. GTC 3. A Registration page with data validation The DOB property has a Range attribute that includes a type argument to indicate that the range is of the Date Time type. Then, it passes two string arguments that indicate the minimum and maximum dates for the range. This code sets the maximum value to a date that’s in the distant future to make sure the current date is always before the maximum value. Later, this chapter presents some techniques for using code to compare a date to the current date. Note that the DOB property is of the Date Time? type, not the Date Time type. This is necessary for the Required attribute to work properly. The Password property has a String Length attribute that only allows string values of 25 characters or less. This attribute doesn’t include a custom validation message because the default message is adequate. In addition, text fields and password fields often prevent the error message from being displayed by not allowing the user to enter more than the specified number of characters. The Password property also has a Compare attribute that tells MVC to check that the value of this property matches the value of the Confirm Password property. This attribute doesn’t include a custom validation message. That’s because the default message for the Compare attribute is adequate here. The Confirm Password property has a Display attribute that adds a space to the property name. As a result, this property displays as “Confirm Password” in the default validation message of the Compare attribute that decorates the Password property. The second code example presents the validation and tags in a strongly-typed view that posts a Customer object to an action method. Here, the tags for the passwords are of the password type. This displays bullets for the characters.
  • 9. GTC
  • 10. GTC  How to control the user experience So far, you’ve learned how to use Bootstrap CSS classes to make messages in a validation summary tag display in red. In addition, you’ve learned how to add your own validation messages to a data attribute. In the next few figures, you’ll learn more skills for controlling how MVC displays validation messages to the user.
  • 11. GTC  How to format validation messages with CSS This HTML includes a data-val attribute with a value of “true”. In addition, it includes several data-val-* attributes that contain information MVC emits for the Required and Regular Expression attributes that decorate the Name property. When data validation fails, MVC also assigns a CSS class named input-validation-error to the tag as shown in the second example. The tags that use the asp-validation-summary tag helper work similarly. For instance, the third example shows that MVC adds a data- valmsgsummary attribute to the tag. In addition, if validation succeeds, it assigns the tag to a CSS class named validation-summary-valid. However, if validation fails, MVC assigns the tag to a CSS class named validation summary-errors as shown by the fourth example. You can define style rules for these CSS classes to control how these tags appear to the user. For instance, the last example presents style rules for all three CSS classes. For tags that have failed validation, the CSS adds a border that’s the same color as the Bootstrap text-danger CSS class. In addition, it adds a background color. The screen at the bottom of this figure shows how such an tag appears on the page. The last two style rules are for validation summary tags. When validation succeeds (or when the page first loads), the first style rule sets the display to none. This hides the tag and prevents it from taking up any space on the page. Then, if you want, you can include a generic message like this and it won’t be displayed unless validation fails:
  • 12. GTC
  • 13. GTC  How to check validation state and use code to set validation messages The Is Valid property returns false if there are any validation messages. The Keys property is a collection that contains the names of the form data parameters that were posted. And the Values property is a collection that contains the values of those parameters. The second table in this figure shows two of the methods of the ModelStateDictionary class. The AddModelError() method adds a validation message. It accepts two string values. The first argument specifies the name of the property that’s associated with the validation message. However, if you want to associate the message with the overall model, you can pass an empty string to this argument. The second argument specifies the validation message itself. The GetValidationState() method returns the validation state of the specified property.
  • 14. GTC Some of the properties of the ModelStateDictionary class Two of the methods of the ModelStateDictionary class Code that adds a validation message to the ModelState property
  • 15. GTC  How to display model-level and property- level validation messages The code below the tables shows how to display model-level messages in one place and property-level messages in another. This action method accepts a Customer object as an argument. As usual, it uses the controller’s ModelState property to check whether validation has succeeded. If not, the code adds another message and associates it with the model. The view has a tag that uses the asp-validation-summary tag helper. This time, though, the code sets the tag helper to “Model Only” rather than “All”. This means that the tag only displays model-level messages like the one added by the action method in this figure. Below the tag, the view includes the tags for the form. Here, each tag is followed by a tag that uses the asp-validation-for tag helper. This HTML sets the value of each tag helper to the same property name that’s bound to the corresponding tag. This means that each tag displays the first property-level message for the specified property. The screen at the bottom of the figure shows what the browser displays when validation fails. Here, the page displays the model-level message that notifies the user that the form contains errors above the form. Then, the property-level messages that describe how to fix the invalid data for each entry display to the right of each text box.
  • 16. GTC  An action method that adds a model-level validation message  Part of a view that displays both model-level and property-level messages
  • 17. GTC  How to enable client-side validation Second, if there’s custom validation on the server, such as the DOB check shown in figure 11-5, validation can run twice. In other words, after the client side validation passes, the form posts to the server, and the server-side validation runs. This can lead to a process where the user gets validation messages in two different steps, which some users might not like. Whenever possible, it’s best to let your users know in one step everything they need to do to fix their data entry. Third, not all of the MVC data attributes work properly with the jQuery validation libraries. In particular, the Range attribute doesn’t work well with dates. For example, in the screen at the bottom of this figure, the user has entered a date of 1/1/1971, which is after 1/1/1900, but the client-side validation is telling the user otherwise. In a case like this, you need to use custom validation as shown later in this chapter. When working with validation, keep in mind that client-side validation is not a substitute for server-side validation. That’s because a user’s browser might have JavaScript turned off, or a malicious user might tamper with the JavaScript. As a result, you should think of client-side validation as a convenience for your users. You should always validate user input on the server as well
  • 18. GTC  Some caveats to client-side validation  It only works correctly with property-level validation, not model-level validation.  Any server-side validation doesn’t run until all client-side validation passes. This can lead to a 2-step process that may annoy some users.  Not all data annotations work properly on the client. In the example below, for instance, the Range annotation for the DOB field isn’t working as it should.
  • 19. GTC  The jQuery libraries in the head section of a Layout view
  • 20. GTC  How to customize server-side validation 1.How to create a custom data attribute To create a custom data attribute, you code a class that inherits the Validation Attribute class and overrides its Is Valid() method as shown by the PastDateAttribute class presented in this figure. It’s a convention to include a suffix of Attribute at the end of the class name. However, you don’t include that suffix when you decorate a model property. The Is Valid() method of the PastDateAttribute class starts by checking whether the value it receives is a date. If so, it casts that value to a Date Time object. Then, it checks whether the date is in the past. If so, the Is Valid() method returns the Success field of the Validation Result class. If the date isn’t in the past, the Is Valid() method returns a new Validation Result object that contains an error message. But first, it builds the message to pass to the constructor of the Validation Result object. To do that, it checks the Error Message property of the base class
  • 21. GTC  A constructor and a field of the Validation Result class  A custom data attribute that checks if a date is in the past
  • 22. GTC  How to pass values to a custom data attribute The Is Valid() method in this figure starts by making sure that the value it receives is a date. If so, it casts this value to a Date Time object. After that, it assigns the current date to a Date Time variable named now and declares another Date Time variable named from. These from and now variables define the range of valid dates. The code then uses the Is Past property to calculate the from variable. If the date is in the past, the code creates a new Date Time value for January 1 of the current year and assigns it to the from variable. Then, this code subtracts the number of years in the numYears variable. So, if the current year is 2020 and the value in numYears is 25, the from date would be 1/1/1995. Conversely, if the date is in the future, the code creates a new Date Time value for December 31 of the current year and assigns it to the from variable. Then, this code adds the number of years in the numYears variable. So, if the current year is 2020 and the value in numYears is 25, the from date will be 12/31/2045
  • 23. GTC  A custom attribute that accept values via a constructor and a property
  • 24. GTC  How to check multiple properties The two custom data attributes you’ve seen so far only check the value of the property they decorate. However, it’s possible to create a data attribute that checks more than one property in the model object. For instance, the RequiredContactInfo data attribute at the top of figure 11-10 checks that a user has entered either a phone number or an email address. To do that, the code in the Is Valid() method uses the Object Instance property of the Validation Context class to return the object that contains the properties being checked. However, it returns it as the object type, so you need to cast it to the correct type. In this example, the code casts the object to the Customer type. To use an attribute like this, you only need to decorate one of the properties it validates with the attribute.
  • 25. GTC  A custom attribute that checks more than one property in a class A custom validation class that checks more than one field
  • 26. GTC  A custom attribute that checks more than one property in a class:-  public class RequiredContactInfoAttribute : ValidationAttribute { protected override ValidationResult IsValid(object v, ValidationContext c){ var cust = (Customer)c.ObjectInstance; if (string.IsNullOrEmpty(cust.PhoneNumber) && string.IsNullOrEmpty(cust.EmailAddress)) { string msg = base.ErrorMessage ?? "Enter phone number or email."; return new ValidationResult(msg); } else { return ValidationResult.Success; } } }
  • 27. GTC  The single method of the IValidatableObject interface  A constructor of the ValidationResult class
  • 28. GTC  How to add data attributes to the generated HTML :-  A method of the IClientModelValidator interface
  • 29. GTC The updated PastDate attribute with client- side validation .
  • 30. GTC  Two constructors of the RemoteAttribute class  A model property with a Remote attribute
  • 31. GTC  The CheckEmail() action method in the Validation controller  One property of the RemoteAttribute class
  • 32. GTC The Registration app with invalid data.
  • 35. GTC  Description  The Customer class provides data validation by decorating its properties with attributes from the System.ComponentModel.DataAnnotations namespace.  The Customer class uses the Remote attribute to use server-side code to check if the email address entered by the user is already in the database. 120  The Customer class uses a custom MinimumAge attribute to check if the user is at least 13 years old.  The RegistrationContext class communicates with a database named Registration. To configure it, you must modify the Startup.cs and appsettings.json files as described in chapter 4.
  • 37. GTC  The Validation controller:
  • 38. GTC  The Register controller
  • 39. GTC  The static Check class
  • 41. GTC Description • The layout includes the jQuery library at the end of the <body> tag, though you can include it in the <head> tag instead if you prefer. • The layout calls the RenderSection() method. This allows individual views to add additional JavaScript files. It places this statement after the <script> tag that includes the jQuery library
  • 43. GTC Description The Register/Index view has a Razor section named scripts that includes the jQuery validation libraries and the minimum-age.js file. That way, these JavaScript files are only loaded for the Registration page, not for other pages of the app that don’t need them.