Friday, October 18, 2019

Server Side Validation in MVC?

The ASP.NET MVC Framework validates any data passed to the controller action that is executing, It populates a ModelState object with any validation failures that it finds and passes that object to the controller. Then the controller actions can query the ModelState to discover whether the request is valid and react accordingly.

I will use two approaches in this article to validate a model data. One is to manually add an error to the ModelState object and another uses the Data Annotation API to validate the model data.

Approach 1 - Manually Add Error to ModelState object

I create a User class under the Models folder. The User class has two properties "Name" and "Email". The "Name" field has required field validations while the "Email" field has Email validation. So let's see the procedure to implement the validation. Create the User Model as in the following,
  1. namespace ServerValidation.Models  
  2. {  
  3.     public class User   
  4.     {  
  5.         public string Name  
  6.       {  
  7.             get;  
  8.             set;  
  9.         }  
  10.         public string Email  
  11.         {  
  12.             get;  
  13.             set;  
  14.         }  
  15.     }  
  16. }  
After that I create a controller action in User Controller (UserController.cs under Controllers folder). That action method has logic for the required validation for Name and Email validation on the Email field. I add an error message on ModelState with a key and that message will be shown on the view whenever the data is not to be validated in the model.
  1. using System.Text.RegularExpressions;  
  2. using System.Web.Mvc;  
  3. namespace ServerValidation.Controllers   
  4. {  
  5.     public class UserController: Controller  
  6.     {  
  7.         public ActionResult Index()   
  8.         {  
  9.                 return View();  
  10.             }  
  11.             [HttpPost]  
  12.         public ActionResult Index(ServerValidation.Models.User model)  
  13.         {  
  14.             
  15.             if (string.IsNullOrEmpty(model.Name))  
  16.             {  
  17.                 ModelState.AddModelError("Name""Name is required");  
  18.             }  
  19.             if (!string.IsNullOrEmpty(model.Email))  
  20.             {  
  21.                 string emailRegex = @ "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +  
  22.                     @ "\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +  
  23.                 @ ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";  
  24.                 Regex re = new Regex(emailRegex);  
  25.                 if (!re.IsMatch(model.Email))  
  26.                 {  
  27.                     ModelState.AddModelError("Email""Email is not valid");  
  28.                 }  
  29.             } else {  
  30.                 ModelState.AddModelError("Email""Email is required");  
  31.             }  
  32.             if (ModelState.IsValid)   
  33.             {  
  34.                 ViewBag.Name = model.Name;  
  35.                 ViewBag.Email = model.Email;  
  36.             }  
  37.             return View(model);  
  38.         }  
  39.     }  
  40. }  
Thereafter I create a view (Index.cshtml) for the user input under the User folder.
  1. @model ServerValidation.Models.User  
  2. @ {  
  3.     ViewBag.Title = "Index";  
  4. }  
  5. @using(Html.BeginForm())   
  6. {  
  7.     if (@ViewData.ModelState.IsValid)  
  8.         {  
  9.         if (@ViewBag.Name != null)  
  10.     { < b >  
  11.                 Name: @ViewBag.Name < br / >  
  12.                 Email: @ViewBag.Email < /b>  
  13.         }  
  14.     } < fieldset >  
  15.         < legend > User < /legend>  < div class = "editor-label" >  
  16.         @Html.LabelFor(model => model.Name) < /div> < div class = "editor-field" >  
  17.         @Html.EditorFor(model => model.Name)  
  18.     @if(!ViewData.ModelState.IsValid) 
  19. < span class = "field-validation-error" > @ViewData.ModelState["Name"].Errors[0].ErrorMessage < /span>   
  20.         
  21. < /div>  < div class = "editor-label" >  

  22.         @Html.LabelFor(model => model.Email) < /div> < div class = "editor-field" >  
  23.         @Html.EditorFor(model => model.Email)  
  24.     @if(!ViewData.ModelState.IsValid)
  25.  {
  26. < span class = "field-validation-error" > @ViewData.ModelState["Email"].Errors[0].ErrorMessage < /span>   
  27.   }      
  28.  < /div> < p >  
  29.         < input type = "submit"  
  30.     value = "Create" / >  
  31.         < /p> < /fieldset>  

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...