Asp.Net MVC 5 Server Side Validation(Visual Studio 2013 RC)

Rama Sagar
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 17161 red flag

Server side validations are required for validating the user input whether it is correct and valid. If the received input data is valid then we do the further processing with the data.

Introduction

This article will help us to learn how to make use of server side validations using explicit model validation.you can check my Previous article on Model validation with Data Annotations  here.

Lets look into the sample implementation

  • Step 1  Lets create the Application as shown in my previous article from here..
        A new property Email in Model class is added

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Serversidevalidation.Models
{
    public class Student
    {
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

  •   Step 2 Now Lets create a empty controller as shown below
       Right click on Controllers Folder-->Add-->Scaffold-->Select MVC5 Controller-Empty -->provide specific name


      Now add the below lines to the controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace Serversidevalidation.Controllers
{
    public class StudentController : Controller
    {
        //
        // GET: /Student/
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(Serversidevalidation.Models.Student model)
        {
            if (string.IsNullOrEmpty(model.Name))
            {
                ModelState.AddModelError("Name", "Name is required");
            }
            if (!string.IsNullOrEmpty(model.Email))
            {
                string emailvalidation = @"^([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(emailvalidation);
                if (!re.IsMatch(model.Email))
                {
                    ModelState.AddModelError("Email", "Provide a valid Email");
                }
            }
            else
            {
                ModelState.AddModelError("Email", "Email is required");
            }
            if (ModelState.IsValid)
            {
                ViewBag.Name = model.Name;
                ViewBag.Email = model.Email;
            }
            return View(model);
        }
    }
}

Here we have used Regular Expression to validate the Email Field and provided the error messages 

using System.Text.RegularExpressions is the Namespace which allows us to use the Regular Expressions

  •  Step 3 Now Lets Create the View for the Model as shown 
        Right click on Views Folder-->Add-->New Folder-->provide name

       Right click on the folder created-->Add-->Scaffold-->MVC5 View-->provide a name-->select Empty Template-- -->select Model class 





  Lets create the view as shown


@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using (Html.BeginForm())
{
    if (@ViewData.ModelState.IsValid)
    {
        if (@ViewBag.Name != null)
        {
            <b>
                Name : @ViewBag.Name<br />
                Email : @ViewBag.Email
            </b>
        }
    }
    <fieldset>
        <legend>Students</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @if (!ViewData.ModelState.IsValid)
            {
                <span class="field-validation-error">@ViewData.ModelState["Name"].Errors[0].ErrorMessage</span>
            }
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @if (!ViewData.ModelState.IsValid)
            {
                <span class="field-validation-error">@ViewData.ModelState["Email"].Errors[0].ErrorMessage</span>
            }
        </div>
        <p>
            <input type="submit" value="Register" />
        </p>
    </fieldset>
}


 Lets check the Preview 

Right click on Index.cshtml and view in browser we can watch the following ouput

When no data is given


When wrong Email is provided



Conclusion

In this article we have learned how to add error manually to model state object



Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)