Monday, October 31, 2016

Client Side Validation in ASP.NET MVC

Client Side Validation in a MVC:
ASP.NET MVC supports client side validation using jquery. First of all you need to take a reference of two javascript files from Scripts folder, jquery.validate.unobtrusive.js (jquery.validate.min.js and jquery.validate.unobtrusive.min.js is minified files) in your layout file.


@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")



As you can see by default in the layout.cs.html(Master page).





Add the following two settings in <appsettings> section of web.config, if it is not there.

Razor Syntax:



<add key="ClientValidationEnabled" value="true"/>

<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

Enabling client side validation for a specific view:

By Adding Html.EnableClientValidation(true)
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
    Html.EnableClientValidation(true);
}



If you working for a single page without master page then

In


Code change in Global.asax.cs file
protected void Application_Start()
{
    HtmlHelper.ClientValidationEnabled = true;
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}


BundleConfig.config:
public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.unobtrusive*",
                "~/Scripts/jquery.validate*"));
}

In View Razor code at bottom:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")

Step 2:

Note: The order in which scripts are referenced is very important. If the order is not correct than it won’t work.

Example:

Create a a new controller (Assume I have created a Employeee Controller)





Create a model in the Model Folder.





public class Employee


    {


        [Required(ErrorMessage = "Employee Id is Required")]


        public int EmployeeRegistrationId { get; set; }



        public DateTime  StartDate { get; set; }



        [Required(ErrorMessage = "Email is Required")]


        [RegularExpression(@"^([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})(\]?)$",


        ErrorMessage = "Email is not valid")]



        public string EmployeeEmailAddress { get; set; }



        [Required(ErrorMessage = "Employee Phone Number is Required")]


        public int EmployeePhoneNumber { get; set; }





        [Required(ErrorMessage = "Employee Password is Required")]


        public string EmployeePassWord { get; set; }
  
    }



Right click on the Controller and Select Add View


@{
    Layout = null;
}
@model Accordion_Menu_MVC.Models.Employee

@{
ViewBag.Title = "Employee Registration Form";
}


<!DOCTYPE html>
<html>
<head>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <div>
            @using (Html.BeginForm())
            {
                     @Html.ValidationSummary(true)
            <fieldset>
               <legend> Employee </legend>
            <div class="editor-field">
                   @Html.EditorFor(model => model.EmployeeRegistrationId)
                   @Html.ValidationMessageFor(model => model.EmployeeRegistrationId)
               </div>
            <div class="editor-label">
                 @Html.LabelFor(model => model.EmployeePhoneNumber)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.EmployeePhoneNumber)
                @Html.ValidationMessageFor(model => model.EmployeePhoneNumber)
            </div>

            <div class="editor-label">
                   @Html.LabelFor(model => model.EmployeeEmailAddress)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.EmployeeEmailAddress)
                @Html.ValidationMessageFor(model => model.EmployeeEmailAddress)
            </div>
                <div class="editor-label">
                    @Html.LabelFor(model => model.EmployeePassWord)
                </div>
                <div class="editor-field">
                    @Html.PasswordFor(model => model.EmployeeEmailAddress)
                    @Html.ValidationMessageFor(model => model.EmployeeEmailAddress)
                </div>
.              <p>
                <input type = "submit" value="Register" />
            </p>
        </fieldset>
            }
        </div>
    </div>
   
</body>
</html>



 Output:


Example 2:
Client Side validations using Data Annotation attribute and jQuery in ASP.Net MVC Razor.
The Client Side validations will be performed using Model class and Data Annotation attributes.
Note: By default the validation done using Data Annotation attributes is Server Side. And hence to make it work Client Side, the Client Side validation must be enabled.

As per MSDN, the Data Annotations attributes cause MVC to provide both client and server validation checks with no additional coding required by you. The Data Annotations attributes can be used with the Entity Data Model (EDM), LINQ to SQL, and other data models.
The Required Data Annotation has been specified with a property Error Message with a string value. As the name suggests, this string value will be displayed to the user when the validation fails.

No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...