Client Side Validation using IClientValidatable in ASP.NET MVC -Part 5


Validation IN MVC – Part FIVE

Validation of input control in Client side validation by applying IClientValidatable in MVC.

In this example I am going to demonstrate you, how to apply a client side script without writing any JavaScript code in the HTML page. This example is very important who is working on MVC real project and then need to apply a client side validation. I will suggest you to follow this approach, I hope you will enjoy after reading this post:

Here is the definition of Controller/HomeController.cs

In Controller we are returning a data to view in the JSON format. We are converting a data in the JSON then we are sending to the view by​​ JsonRequestBehavior.AllowGet​​ property in the JSON Method. Please see the below HomeController.cs.

using​​ System;

using​​ System.Web.Mvc;

 

namespace​​ DotNetMindsWebBlogPost.Controllers

{

 ​​ ​​ ​​​​ public​​ class​​ HomeController​​ :​​ Controller

 ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ ActionResult​​ Index()

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ View();

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ [HttpPost]

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ ActionResult​​ Index(Appointment​​ appt)

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ if​​ (ModelState.IsValid)

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ View("JobDone", appt);

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ else

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ View();

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 

 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ JsonResult​​ ValidateDate(string​​ Date)

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ DateTime​​ parsedDate;

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ if​​ (!DateTime.TryParse(Date,​​ out​​ parsedDate))

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ Json("Please enter a valid date (mm/dd/yyyy)",

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ JsonRequestBehavior.AllowGet);

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ else​​ if​​ (DateTime.Now > parsedDate)

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ Json("Please enter a date in the future",​​ JsonRequestBehavior.AllowGet);

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ else

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ Json(true,​​ JsonRequestBehavior.AllowGet);

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​​​ }

}

 

Here is the definition of Model/AppointmentCodeFile.cs

If you see the model class , Field EmailAddress has ben decorated ​​ as a attribute [EmailAddressAttribute] which I am going to discuss later​​ , for date it is decorated with the attribute Remote , which it allows to generate a client script on the UI page.

 

For more on Remote Attribute: As per MSDN,​​ ASP.NET MVC provides a mechanism that can make a remote server call in order to validate a form field without posting the entire form to the server. This is useful when you have a field that cannot be validated on the client and is therefore likely to fail validation when the form is submitted. 

 

using​​ System;

using​​ System.ComponentModel.DataAnnotations;

using​​ System.Web.Mvc;

namespace​​ DotNetMindsWebBlogPost

{

 ​​ ​​ ​​​​ public​​ class​​ Appointment

 ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​​​ [EmailAddressAttribute()]

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ string​​ EmailAddress {​​ get;​​ set; }

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ [DataType(DataType.Date)]

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ [Remote("ValidateDate",​​ "Home")]

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ DateTime​​ Date {​​ get;​​ set; }

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ [MustBeTrueAttribute(ErrorMessage="You Must Accept the terms")]

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ bool​​ TermsAccepted {​​ get;​​ set; }

 ​​ ​​ ​​ ​​ ​​ ​​​​ 

 ​​ ​​ ​​​​ }

}

 

Some Recommended Book for MVC​​ , AngularJS

Professional AngularJS ​​  ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ ​​ Professional ASP.NET MVC 5

https://ws-in.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=B00WGANARC&Format=_SL160_&ID=AsinImage&MarketPlace=IN&ServiceVersion=20070822&WS=1&tag=dotnetmindsco-21 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ http://ws-in.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=8126551925&Format=_SL160_&ID=AsinImage&MarketPlace=IN&ServiceVersion=20070822&WS=1&tag=dotnetmindsco-21

 

Here is the definition of Infrastructure/MustbeTrueCodeFile.cs

Here if you see I am inheriting a ValidationAttribute as well as implementing the IClientValidatable interface rule in the class MustBeTrueAttribute.

We are overriding the method GetClientValidationRules​​ .

It is returing a client business rule in the form of ModelClientValidationRule[] with the help ModelMetaData and ControllerContext. As per model rule declared in the appointmentcodefile , it is fetching the rule and rendering in the UI page.

 

 

using​​ System.Collections.Generic;

using​​ System.ComponentModel.DataAnnotations;

using​​ System.Text.RegularExpressions;

using​​ System.Web.Mvc;

namespace​​ DotNetMindsWebBlogPost

{

 ​​ ​​ ​​​​ public​​ class​​ MustBeTrueAttribute​​ :​​ ValidationAttribute,​​ IClientValidatable

 ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ override​​ bool​​ IsValid(object​​ value)

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ value​​ is​​ bool​​ && (bool)value;

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata​​ metadata,​​ ControllerContext​​ context)

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ new​​ ModelClientValidationRule[] {​​ 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ new​​ ModelClientValidationRule​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ ValidationType =​​ "checkboxtrue",

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ ErrorMessage =​​ this.ErrorMessage

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ };

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​​​ }

 

 ​​ ​​ ​​​​ public​​ class​​ EmailAddressAttribute​​ :​​ ValidationAttribute,​​ IClientValidatable

 ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ private​​ static​​ readonly​​ Regex​​ emailRegex =​​ new​​ Regex(".+@.+\\..+");

 

 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ EmailAddressAttribute()

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ ErrorMessage =​​ "Enter a valid email address";

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ override​​ bool​​ IsValid(object​​ value)

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ !string.IsNullOrEmpty((string)value) &&

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ emailRegex.IsMatch((string)value);

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ public​​ IEnumerable<ModelClientValidationRule> GetClientValidationRules(

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ ModelMetadata​​ metadata,​​ ControllerContext​​ context)

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ {

 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ return​​ new​​ List<ModelClientValidationRule> {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ new​​ ModelClientValidationRule​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ ValidationType =​​ "email",

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ ErrorMessage ​​ =​​ this.ErrorMessage

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ },​​ 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ new​​ ModelClientValidationRule​​ {

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ ValidationType =​​ "required",

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ ErrorMessage =​​ this.ErrorMessage

 ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ };

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ }

 ​​ ​​ ​​​​ }

}

 

Here is the definition of View/Index.cshtml

@model​​ DotNetMindsWebBlogPost.Appointment

 

@{

 ​​ ​​ ​​​​ ViewBag.Title =​​ "Index";

}

 

<h2>Book An Appointment</h2>

@Html.ValidationSummary(false)

@using​​ (Html.BeginForm())

{

 ​​ ​​ ​​​​ <p>Email Address :​​ @Html.EditorFor(m=>m.ClinicName)

 ​​ ​​ ​​ ​​​​ @Html.ValidationMessageFor(m=>m.ClinicName)</p>

 ​​ ​​ ​​​​ <p>

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ Appointment Date:​​ @Html.EditorFor(m => m.Date)

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ @Html.ValidationMessageFor(m => m.Date)

 ​​ ​​ ​​​​ </p>

 ​​ ​​ ​​​​ <p>@Html.EditorFor(m => m.TermsAccepted) I accept the terms & conditions

 ​​ ​​ ​​​​ 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ @Html.ValidationMessageFor(m => m.TermsAccepted)</p>

 ​​ ​​​​ <input​​ type="submit"​​ value="Make Booking"​​ />

}

 

Here is the source page code after rendering the UI to the browser .

To Understand the code logic which is doing by IclientValidatable interface , I am here sharing the UI page source code and see how th client scripting has been generated in the pagae.

 

 

<!DOCTYPE html>​​ 

 

<html>​​ 

 

<head>​​ 

 

<meta​​ charset="utf-8" />​​ 

 

<meta​​ name="viewport"​​ content="width=device-width" />​​ 

 

<title>Index</title>​​ 

 

<link​​ href="/Content/site.css"​​ rel="stylesheet"/>​​ 

 

 

 

<script​​ src="/Scripts/jquery-1.8.2.js"></script>​​ 

 

 

 

<script​​ src="/Scripts/jquery.validate.min.js"></script>​​ 

 

<script​​ src="/Scripts/jquery.validate.unobtrusive.min.js"></script>​​ 

 

<script​​ type="text/javascript">​​ 

 

 

 

jQuery.validator.unobtrusive.adapters.add("checkboxtrue", function (options) {​​ 

 

if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {​​ 

 

options.rules["required"] = true;​​ 

 

if (options.message) {​​ 

 

options.messages["required"] = options.message;​​ 

 

}​​ 

 

}​​ 

 

});​​ 

 

</script>​​ 

 

</head>​​ 

 

<body>​​ 

 

 

 

 

 

<h2>Book An Appointment</h2>​​ 

 

<div​​ class="validation-summary-valid"​​ data-valmsg-summary="true"><ul><li​​ style="display:none"></li>​​ 

 

</ul></div>​​ 

 

<form​​ action="/"​​ method="post">​​ <p>Email Address :​​ <input​​ class="text-box single-line"​​ data-val="true"​​ data-val-email="Enter a valid email address"​​ data-val-required="Enter a valid email address"​​ id="ClinicName"​​ name="ClinicName"​​ type="text"​​ value=""​​ />​​ 

 

<span​​ class="field-validation-valid"​​ data-valmsg-for="ClinicName"​​ data-valmsg-replace="true"></span></p>​​ 

 

<p>​​ 

 

Appointment Date:​​ <input​​ class="text-box single-line"​​ data-val="true"​​ data-val-date="The field Date must be a date."​​ data-val-remote="&#39;Date&#39; is invalid."​​ data-val-remote-additionalfields="*.Date"​​ data-val-remote-url="/Home/ValidateDate"​​ data-val-required="The Date field is required."​​ id="Date"​​ name="Date"​​ type="date"​​ value="" />​​ 

 

<span​​ class="field-validation-valid"​​ data-valmsg-for="Date"​​ data-valmsg-replace="true"></span>​​ 

 

</p>​​ 

 

<p><input​​ class="check-box"​​ data-val="true"​​ data-val-checkboxtrue="You Must Accept the terms"​​ data-val-required="The TermsAccepted field is required."​​ id="TermsAccepted"​​ name="TermsAccepted"​​ type="checkbox"​​ value="true" /><input​​ name="TermsAccepted"​​ type="hidden"​​ value="false" />​​ I accept the terms & conditions​​ 

 

 

 

<span​​ class="field-validation-valid"​​ data-valmsg-for="TermsAccepted"​​ data-valmsg-replace="true"></span></p>​​ 

 

<input​​ type="submit"​​ value="Make Booking" />​​ 

 

</form>​​ 

 

 

 

 

 

</body>​​ 

 

</html>​​ 

 

 

​​ Below are the output screen for he above example :

If you press any text in the textbox, client script will start to work.

 

Hope you enjoyed the above all post on Validation in MVC.:​​ ​​ If you liked make a comment on the post.


Know more on validation :  Different Types of Validations in ASP.NET MVC with Examples


Recommended Book for MVC : List of Some Important books for .NET Framework, C#, MVC, WCF


(Visited 1,435 times, 2 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *