I\'m trying to implement the code as mentioned in this post. In other words I\'m trying to implement unobtrusive validation on a terms and conditions checkbox. If the user
You need to implement IClientValidatable on your custom attribute in order to tie the mustbetrue adapter name that you are registering on the client side with this attribute:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
return value != null && value is bool && (bool)value;
}
public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "mustbetrue"
};
}
}
UPDATE:
Full working example.
Model:
public class MyViewModel
{
[MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
[DisplayName("Accept terms and conditions")]
public bool AcceptsTerms { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.CheckBoxFor(x => x.AcceptsTerms)
@Html.LabelFor(x => x.AcceptsTerms)
@Html.ValidationMessageFor(x => x.AcceptsTerms)
}