MVC Learning Series 10 --- server verification of the Verification Series, mvc10 ---
In this article, I will talk about using the data annotation API for server-side verification. ASP. net mvc Framework verifies all data transmitted to the controller during execution. If the verification fails, it fills in the error message to the ModelState object and passes the object to the Controller, then, the method in the Controller determines whether the verification fails or passes Based on the Modelstate status.
Here, I will use two methods to verify the validity of Data. One is to manually add an error message to the ModelState object, and the other is to use the Data Annotation [Data Annotation] API,.
Let's take a look at the manual verification method:
Create a blank MVC project: Add a Student object:
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Server_Side_Validation_IN_MVC.Models{ public class Student { public string Name { get; set; } public string Email { get; set; } }}
Then add a Student controller:
Using Server_Side_Validation_IN_MVC.Models; using System. collections. generic; using System. linq; using System. text. regularExpressions; using System. web; using System. web. mvc; namespace Server_Side_Validation_IN_MVC.Controllers {public class StudentController: Controller {// GET: Student public ActionResult Index () {return View ();} [HttpPost] public ActionResult Index (Student model) {// server Server verification, Method 1: manually add an error message to the ModelState object // if the Name is empty if (string. isNullOrEmpty (model. name) {ModelState. addModelError ("Name", "Name is required");} // if the Email is empty if (string. isNullOrEmpty (model. email) {ModelState. addModelError ("Email", "Email is required");} else {string emailRegex = @ "^ ([a-zA-Z0-9 _ \-\.] +) @ (\ [0-9] {1, 3} "+ @"\. [0-9] {1, 3 }\. [0-9] {1, 3 }\.) | ([a-zA-Z0-9 \-] + \ "+ @".) +) ([a-zA-Z] {2, 4} | [0-9] {1, 3}) (\]?) $ "; Regex re = new Regex (emailRegex); // when the Email is not empty, but the format is invalid if (! Re. isMatch (model. email) {ModelState. addModelError ("Email", "Email is not valid") ;}// entity verification passes if (ModelState. isValid) {ViewBag. name = model. name; ViewBag. email = model. email;} return View (model );}}}
Create an Index View:
@ Model Server_Side_Validation_IN_MVC.Models.Student @ {Layout = null;} <! DOCTYPE html> Correct syntax:
@ If (! ViewData. modelState. isValid & ViewData. modelState ["Email"]. errors. count> 0) {// get the error message from the dictionary: @ ViewData. modelState ["Name"]. errors [0]. errorMessage <span style = "color: red"> @ ViewData. modelState ["Name"]. errors [0]. errorMessage </span >}</div> <div> @ Html. labelFor (model => model. email) </div> <div> @ Html. editorFor (model => model. email) // @ if (! ViewData. ModelState. IsValid:
// The correct statement is as follows:
@ If (! ViewData. modelState. isValid & ViewData. modelState ["Email"]. errors. count> 0) {// get the error message from the dictionary: @ ViewData. modelState ["Email"]. errors [0]. errorMessage <span style = "color: red"> @ ViewData. modelState ["Email"]. errors [0]. errorMessage </span >}</div> <p> <input type = "submit" value = "Create"/> </p> </fieldset >}</div> </body>
Then, modify the default route:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional } ); }
Run the project:
First, verify that no data is input. Click Create:
Then verify that the Name has a value, while the Email has no value:
After running, an error is reported. After finding the cause, I modified the view code:
After running,
Next, verify that the Name is not empty and the Email enters invalid data format:
Finally, verify that valid data is entered:
Now let's look at the second method., Using data annotations for server Verification:
Create a new class: avoid confusion,
Using System; using System. collections. generic; using System. componentModel. dataAnnotations; using System. linq; using System. web; namespace Server_Side_Validation_IN_MVC.Models {public class StudentServer {[Required (ErrorMessage = "Name is Required")] public string Name {get; set ;} [Required (ErrorMessage = "Email Required")] [EmailAddress (ErrorMessage = "Incorrect Email format")] public string Email {get; set ;}}}
Create two methods in the controller:
public ActionResult SeverSideIndex() { return View(); } [HttpPost] public ActionResult SeverSideIndex(StudentServer model) { if (ModelState.IsValid) { ViewBag.Name = model.Name; ViewBag.Email = model.Email; } return View(); }
View:
@model Server_Side_Validation_IN_MVC.Models.StudentServer@{ Layout = null;}@if (ViewData.ModelState.IsValid){ if (ViewBag.Name != null) { <b> Name:@ViewBag.Name<br /> Email:@ViewBag.Email </b> }}<!DOCTYPE html>
Run:
First, verify that all values are empty:
Name is not empty, Email is empty
Name is not blank. Invalid format data is entered by Email
Both of them enter valid data:
Well, the above is the server verification in MVC. We generally use the second method for verification. That is, data annotation.
Summary:
Server side validations ensure that the specified ed data is correct and valid. if the specified ed data is valid then we do further processing with the data. server side validations are very important before playing with sensitive information of a user.
Server-side validation must be done whether we validate the received data on the client side. user cocould disable script in his browser or do something else to bypass client-side validation. in this case server-side validation must require to protect our data from dirty input.