Reader small image

You're reading from  Learning ASP.NET Core MVC Programming

Product typeBook
Published inNov 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781786463838
Edition1st Edition
Languages
Right arrow
Authors (2):
Mugilan T. S. Ragupathi
Mugilan T. S. Ragupathi
author image
Mugilan T. S. Ragupathi

Mugilan T. S. Ragupathi has been working on building web-based applications using Microsof technology for more than a decade. He is active in the ASP.NET community and is running a successful blog, www.dotnetodyssey.com, to help his fellow .NET developers. His free beginners' course for ASP.NET MVC 5 (http://www.dotnetodyssey.com/asp-net-mvc-5-free-course/) was well received and is referred to as a concrete reference for beginners. He can be seen on subreddit / Stack Overflow in the C# section. He has written two free micro e-books, The 7 Most Popular Recipes of jQuery with ASP.NET Web Forms and Value & Reference types in C# (http://www.dotnetodyssey.com/freeebooks/). His books have received good responses. He is also an active contributor to the ASP.NET community on Quora (https://www.quora.com/profile/Mugil-Ragu). He likes to help readers with queries regarding ASP.NET.
Read more about Mugilan T. S. Ragupathi

Anuraj Parameswaran
Anuraj Parameswaran
author image
Anuraj Parameswaran

Anuraj Parameswaran is a seasoned IT expert with over 19 years of experience, starting in 2004, with a strong focus on Azure and .NET technologies. Currently serving as the Chief Technology Officer (CTO) of Socxo Solutions Pvt. Ltd., he has received seven prestigious Microsoft MVP awards. Anuraj actively participates in mentoring programs, delivers speeches at various events, and contributes extensively to both Microsoft and Azure communities. His commitment to sharing knowledge and embracing lifelong learning is exemplified by his involvement as a technical reviewer for Packt books.
Read more about Anuraj Parameswaran

View More author details
Right arrow

Chapter 6. Validation

We can never rely on the data entered by users. Sometimes they might be ignorant about the application and thus they may be entering incorrect data unknowingly. At other times, some malign users may want to corrupt the application by entering inappropriate data into it. In either case, we need to validate the input data before storing the data for further processing.

In this chapter, you'll be learning about the following topics:

  • Different types of validation

  • Server-side validation with an example

  • Client-side validation with an example

  • Unobtrusive JavaScript validation using jQuery unobtrusive libraries, where we don't have to write separate code for validation

In an ideal case, users will enter valid data in a proper format in your application. But, as you might realize, the real world is not so ideal. Users will enter incorrect data in your application. As a developer, it is the responsibility of us to validate the user input in our application. If the entered input is...

Client-side and server-side validation


In the real world, it's not a case of either server-side or client-side validation. We can have both types of validation at the same time. In fact, it is recommended to validate the data at both ends to avoid unnecessary processing.

The preceding figure shows the validation is being performed at both the client-side and the server-side. If the data is not entered into the required field, we can catch that issue at the client-side itself. There is no need to send the data to the server to finally find out that there is no data entered. Once all the required data is entered, the data is sent back to the server to validate the entered data based on some business logic. If the validation fails, the form data is sent again to the browser with the error message so that the user can send the data again.

We have covered enough theory about the need for validation and the types of validations typically used in the application. Let us get our hands dirty by adding...

Server-side validation


Let us continue with the application that we built in the previous chapter. To do server-side validation, we need to do the following:

  1. Add Data Annotation attributes to the ViewModels model class. The input data is validated against this metadata and the model state is updated automatically.

  2. Update the view method to display the validation message for each of the fields. The span tag helper with the asp-validation-for attribute will be used to display the validation error message.

  3. Update the controller action method to verify the model state. If the model state is valid, we insert the data into the database. Otherwise, the View model is updated and the view method is rendered again with the validation error message so that the user can update with valid input data and submit the form again.

Updating View models with the Data Annotation attribute

The Data Annotation attributes defines the validation rules for the properties of the Model/ViewModel. If the input data does...

Client-side validation


There are scenarios where we don't need to go to the server to validate the input data. In the preceding example of the server-side validation, we do not need to go to the server to verify whether the user has entered the data for the Name field. We can validate at the client-side itself. This prevents round-trips to the server and reduces the server load.

We are going to use JavaScript to validate the data from the client-side. JavaScript is a high-level, interpreted language which is primarily used in client-side programming.

Note

These days, JavaScript is also being used at the server-side as part of Node.js.

We are going to make a couple of changes in our View model (Index.cshtml file) to validate the form at the client-side:

  1. Changes in the form: add the id attribute to all the span tags so that we can access this HTML element to display the HTML error message. On submission of the form, call a JavaScript function to validate the input data.

  2. Add the script HTML element...

Implementation


There will be a layout file (_Layout.cshtml) to define the layout structure of your web application. As JavaScript libraries are going to be used in all the pages, this is the right place to add common functionalities such as unobtrusive validation. Just add the JavaScript libraries (highlighted in bold) to the layout file (_Layout.cshtml) so that they will be available for all the View files:

<!DOCTYPE html> 
<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>@ViewBag.Title</title> 
</head> 
<body> 
    <div> 
        @RenderBody() 
    </div> 
 
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.3.js"></script> 
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script> 
    <script src="https://ajax.aspnetcdn.com/ajax/mvc/5.2...

Summary


In this chapter, we have learned about the need for validation and the different kinds of validation available. We have even discussed how client-side and server-side validation work, along with the pros and cons of each type of validation. Later, we made code changes to validate the input data at the server-side. Then we used JavaScript to validate the input data in the client-side itself. Finally, we used the jQuery unobtrusive library to do the client-side validation without ever writing the JavaScript code to validate the input data at the client-side.

In the next chapter, we will discuss the routing principle and how to customize it. In an earlier chapter, we saw the basics of routing in an ASP.NET 5 application. Now we are going to explore the topic in depth.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning ASP.NET Core MVC Programming
Published in: Nov 2016Publisher: PacktISBN-13: 9781786463838
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (2)

author image
Mugilan T. S. Ragupathi

Mugilan T. S. Ragupathi has been working on building web-based applications using Microsof technology for more than a decade. He is active in the ASP.NET community and is running a successful blog, www.dotnetodyssey.com, to help his fellow .NET developers. His free beginners' course for ASP.NET MVC 5 (http://www.dotnetodyssey.com/asp-net-mvc-5-free-course/) was well received and is referred to as a concrete reference for beginners. He can be seen on subreddit / Stack Overflow in the C# section. He has written two free micro e-books, The 7 Most Popular Recipes of jQuery with ASP.NET Web Forms and Value & Reference types in C# (http://www.dotnetodyssey.com/freeebooks/). His books have received good responses. He is also an active contributor to the ASP.NET community on Quora (https://www.quora.com/profile/Mugil-Ragu). He likes to help readers with queries regarding ASP.NET.
Read more about Mugilan T. S. Ragupathi

author image
Anuraj Parameswaran

Anuraj Parameswaran is a seasoned IT expert with over 19 years of experience, starting in 2004, with a strong focus on Azure and .NET technologies. Currently serving as the Chief Technology Officer (CTO) of Socxo Solutions Pvt. Ltd., he has received seven prestigious Microsoft MVP awards. Anuraj actively participates in mentoring programs, delivers speeches at various events, and contributes extensively to both Microsoft and Azure communities. His commitment to sharing knowledge and embracing lifelong learning is exemplified by his involvement as a technical reviewer for Packt books.
Read more about Anuraj Parameswaran