I am using ASP.NET MVC 5 and on the client side want to use JQuery unobtrusive validation.
Following is my model:
public class CompanyModel { public CompanyModel() { Employees = new List<EmployeeModel>(); } public int CompanyId{ get; set; } public List<EmployeeModel> Employees { get; set; } } public class EmployeeModel { public EmployeeModel() { Values = new List<string>(); } public string Id { get; set; } public string Name { get; set; } [RequiredIf("IsRequired", true, "Atleast one value is required")] public List<string> Values { get; set; } public bool IsRequired { get; set; } }
I was able to implement the RequiredIf custom attribute successfully on the server side. But I'm struggling to get the client side validation going...
In the view I loop through the employees list and the values collection is bound
@for (var index = 0; index < Model.Employees.Count; index++) { /// some other code @for (int i = 0; i < Model.employees[index].Values.Count; i++) { @Html.TextBoxFor(m => m.Employees[index].Values[i], new {@autocomplete = "false" }) } }
The IsRequired property is a hidden field:
@Html.HiddenFor(m => m.Employees[index].IsRequired)
The following is the code I have so far for the GetClientValidationRules method.
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = ErrorMessage, ValidationType = "requiredif" }; rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty); rule.ValidationParameters["dependentpropertyvalue"] = DependentPropertyValue.ToString().ToLower(); yield return rule; }
I don't see the validation html (data-val-*) attributes added to the values in the HTML markup. And I don't expect them too as I think I am missing something. How do I get all the elements of the values collection populated with the data-val-requiredif attributes in html.
Any ideas?
FYI: the dependentpropertyId in html is populated like so CompanyModel.Employees_0_IsRequired for Employee[0].
List<string>
is supposed to be. However, using jQuery Validate, you can only validatetextarea
,select
, and various types ofinput
elements; nothing else.