I have a required annotation on my model:
[Required(ErrorMessage = \"Please choose an option\")]
public bool? AnyDebts { get; set; }
I have
Take a look on this code.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class RequiredIfAttribute : RequiredAttribute
{
public string PropertyName { get; set; }
public Enums.BasicOperationType BasicOperationType { get; set; }
public RequiredIfAttribute(string propertyName, Enums.BasicOperationType BasicOperationType)
{
this.PropertyName = propertyName;
this.BasicOperationType = BasicOperationType;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
Type objectType = validationContext.ObjectType;
PropertyInfo[] neededProperties = objectType.GetProperties().Where(propertyInfo => propertyInfo.Name == PropertyName).ToArray();
if (Core.Helpers.EnumHelper.TryParse<Enums.BasicOperationType>(Convert.ToInt16(neededProperties[0].GetValue(validationContext.ObjectInstance, null))) == BasicOperationType)
return base.IsValid(value, validationContext);
return base.IsValid(0, validationContext);
}
}
For my case, it only happens when using IE in quirks mode, my settings are Browser Mode: IE9, Document Mode: Quirks. This results in client side validation not working for me. However, the same page works well in Firefox,Chrome, and IE9, Browser Mode: IE9, Document Mode: IE9 standards when using the developer toolbar. Not that its a solution, but a possible lead
<script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
are the only required scripts for client validation to work.
And as always here's a full working demo:
Model:
public class MyViewModel
{
[Required(ErrorMessage = "Please choose an option")]
public bool? AnyDebts { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
@model AppName.Models.MyViewModel
@{
ViewBag.Title = "Home Page";
}
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
<div>Debts</div>
<span>Yes</span> @Html.RadioButtonFor(x => x.AnyDebts, true)
<span>No</span> @Html.RadioButtonFor(x => x.AnyDebts, false)
@Html.ValidationMessageFor(x => x.AnyDebts)
<input type="submit" value="OK" />
}
Remark: I haven't included jquery-1.4.4.js
in my view because it is already referenced in the layout.