Server Side Model Validation in MVC 4 Razor

Ravikumar
0

Serever Side Model Validation 

  • Server Side validations are required for ensuring that the entered data is correct and valid as required.
  • If the received date is valid ,then the application will allow to continue with process else show thwe errors to user

Server-side Validation ??

   Some user may disable script in his his/her browser ,In this case we must require to validate our data or values from unwanted values from the user. to avoid this we can use server side validations.

We can validate "Using MODEL" in server side by two different ways:
  •  Model Validation with Data Annotations
  •  (Like using System.ComponentModel.DataAnnotations;)
  • Explicit Model Validation 
For  DataAnnotation Validation Click Here
Here We go step wise Step:

Crete new MVC 4 project as shown below:

 
Select MVC 4:
Select Internet Application :

Now Go to Model folder and add new User.cs Class:


Rename it using User.cs:

Type Givan below code in User.cs

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

namespace Mvc4SereverSideValidation.Models
{
    public class User
    {
        public string UserName { get; set; }

        public string Password { get; set; }

        public string Address { get; set; }

        public string MobileNo { get; set; }

        public string EMailID { get; set; }

        //for security Question Answer
        public string Answer { get; set; }

        public bool TermsAndCondtionAccepted { get; set; }
    }
}

Now goto controoler folder and Add New controller:
Select Empty MVC controller:

Now type given code in UserController.cs

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

namespace Mvc4SereverSideValidation.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult Index(User userDetails)
        {
            if (Request.HttpMethod == "POST")
            {
                if(string.IsNullOrEmpty(userDetails.UserName))
                {
                    ModelState.AddModelError("UserName","Please Enter UserName");
                }
                if (!string.IsNullOrEmpty(userDetails.UserName))
                {
                    Regex emailRegex = new Regex("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$");
                    if (!emailRegex.IsMatch(userDetails.UserName))
                    {
                        ModelState.AddModelError("UserName", "Please Enter Valid UserName.");
                    }
                }
                if (string.IsNullOrEmpty(userDetails.Password))
                {
                    ModelState.AddModelError("Password","Please Enter Password.");
                }
                if (string.IsNullOrEmpty(userDetails.Address))
                {
                    ModelState.AddModelError("Address","Please Enter Address.");
                }
                if (string.IsNullOrEmpty(userDetails.MobileNo))
                {
                    ModelState.AddModelError("MobileNo", "Please Enter MobileNo.");
                }
                if (string.IsNullOrEmpty(userDetails.EMailID))
                {
                    ModelState.AddModelError("EMailID", "Please Enter EMailID.");
                }
                if (string.IsNullOrEmpty(userDetails.Answer))
                {
                    ModelState.AddModelError("Answer", "Please Enter Answer.");
                }
                if (!userDetails.TermsAndCondtionAccepted)
                {
                    ModelState.AddModelError("TermsAndCondtionAccepted", "Please Accept Terms and Conditions.");
                }
                if (ModelState.IsValid)
                {
                    return View("SuccessPage");
                }
                else
                {
                    return View();
                }
            }
            return View();
        }

    }
}

Add New view by right clicking on Index():
Select Model class User.cs:

You will see code like this in Index.cshtml

@model Mvc4SereverSideValidation.Models.User

@{
    ViewBag.Title = "Server Side Model Validation in MVC 4 Razor";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Server Side Model Validation in MVC 4 Razor</h2>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>User</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.MobileNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.MobileNo)
            @Html.ValidationMessageFor(model => model.MobileNo)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.EMailID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EMailID)
            @Html.ValidationMessageFor(model => model.EMailID)
        </div>
        <div class="editor-label">
            <b>Select Question</b>
        </div>
        <div class="editor-label">



            @{var listItems = new List<System.Web.UI.WebControls.ListItem>
            {
              new System.Web.UI.WebControls.ListItem { Text = "-- Select Question --", Value="0" },
              new System.Web.UI.WebControls.ListItem { Text = "What's your pet Name?", Value="1" },
              new System.Web.UI.WebControls.ListItem { Text = "Which is your first School?", Value="2" },
              new System.Web.UI.WebControls.ListItem { Text = "What's your first ?", Value="3" }
            };
            }
            @Html.DropDownList("Exemplo", new SelectList(listItems, "Value", "Text"))


        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Answer)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Answer)
            @Html.ValidationMessageFor(model => model.Answer)
        </div>

     
        <div class="editor-field">
            @Html.EditorFor(model => model.TermsAndCondtionAccepted)
            @Html.ValidationMessageFor(model => model.TermsAndCondtionAccepted)
        </div>
          <div class="editor-label">
            @Html.LabelFor(model => model.TermsAndCondtionAccepted)
        </div>

        <p>
            <input type="submit" value="submit" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Add Empty page and give name like this SuccessPage.cshtml:


@model Mvc4SereverSideValidation.Models.User

@{
    ViewBag.Title = "SuccessPage";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>SuccessPage</h2>


Change in  RouteConfig.cs

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

namespace Mvc4SereverSideValidation
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "User", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


Now Run this application :





















Notes :

"  I hope you have created your MVC 4 application successfully and If you like my work  you can appreciate by leaving your comments and updates ".


Download Source From Here


                                                                       


Tags:

Post a Comment

0Comments

Post a Comment (0)