Watch this example on YouTube
1. Layout
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/Scripts/CustomValidation.js")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
2. Model - Validator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Reflection;
namespace WebApplication10.Models
{
public class ValidateCheckBoxAttribute: ValidationAttribute, IClientValidatable
{
private readonly string[] _fields;
private const string DefaultErrorMessage = "{0} is mandatory";
public string firstPropertyName { get; set; }
public ValidateCheckBoxAttribute(string[] fields)
{
_fields = fields;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo propertyFirst = validationContext.ObjectType.GetProperty(_fields[0]);
PropertyInfo propertySecond = validationContext.ObjectType.GetProperty(_fields[1]);
var valueFirst = propertyFirst.GetValue(validationContext.ObjectInstance, null);
var valueSecond = propertySecond.GetValue(validationContext.ObjectInstance, null);
if(valueSecond == null & Convert.ToBoolean(valueFirst)== true)
{
return new ValidationResult("" + validationContext.DisplayName + " is mandatory");
}
return null;
}
public IEnumerable<ModelClientValidationRule>
GetClientValidationRules(ModelMetadata metadata, ControllerContext
context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "validatecheckbox",
ErrorMessage = metadata.GetDisplayName() + " is mandatory(client error)"
};
rule.ValidationParameters.Add("fields", string.Join(",", _fields));
yield return rule;
}
}
}
3. Javascript validator
$.validator.unobtrusive.adapters.add("validatecheckbox", ["fields"], function (options) {
var element = options.element;
var otherNames = options.params.fields.split(',');
var fields = [];
$.each(otherNames, function (index, item) {
fields.push(ElementDetails.getElementDetails(element, item))
});
options.rules['validatecheckbox'] = {
fields: fields
};
options.messages['validatecheckbox'] = options.message;
});
$.validator.addMethod('validatecheckbox', function (value, element, params) {
if ($(element).val() != '') {
return true;
}
var isValid = true;
if ($(params)[0].fields[0][0].checked == true) {
if (($(element).val() == '' || $(element).val() == null)) {
isValid = false;
}
}
return isValid;
});
ElementDetails = {
getElementDetails: function (validationElement, item) {
var retElement = $('#' + item);
if (retElement.length === 1) {
return retElement;
}
var name = validationElement.name;
var index = name.lastIndexOf(".") + 1;
var id = (name.substr(0, index) + item).replace(/[\.\[\]]/g, "_");
retElement = $('#' + id);
if (retElement.length === 1) {
return retElement;
}
return null;
}
}
4. Model - Customer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication10.Models
{
public class Customer
{
[ValidateCheckBox(new string[] { "IsActive", "FirstName"})]
public string FirstName { get; set; }
public bool IsActive { get; set; }
}
}
5. Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication10.Models;
namespace WebApplication10.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Customer model = new Customer();
return View(model);
}
[HttpPost]
public ActionResult Index(Customer model)
{
if (!ModelState.IsValid) { }
return View(model);
}
6. Index
@model WebApplication10.Models.Customer
@{ Html.EnableClientValidation();}
@using(Html.BeginForm(null, null, FormMethod.Post))
{
@Html.AntiForgeryToken();
@Html.CheckBoxFor(x => x.IsActive)
@Html.TextBoxFor(x => x.FirstName)
@Html.ValidationMessageFor(x => x.FirstName)
<input type="submit" value="SUBMIT" />
}
No comments:
Post a Comment