I have a model in which an employee contains a list of functions. The employee should at least have one function.
public class Employee
{
[Required(ErrorMessage = "Name is Required")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is Required")]
[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
ErrorMessage = "Email is not valid")]
public string Email { get; set; }
[Required(ErrorMessage = "At least one function is required")]
public List<Function> Functions { get; set; }
}
public class Function
{
[Required(ErrorMessage = "Name is Required")]
public string Name { get; set; }
}
I've created an EditorTemplate for a Function
@model MvcClientSideValidation.Models.Function
<fieldset>
<legend>Functie</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</fieldset>
The Index view uses the EditorFor and a ValidationMessageFor.
@Html.EditorFor(m => m.Functions)
@Html.ValidationMessageFor(m => m.Functions)
The view also contains code to add or delete a function.
When the view is submitted, client-side validation does not check if a function is present. Server-side validation does. The problem is that when the list is empty, no input elements are rendered for the Function
property, so there are no tags to which the validation tags can be added.
So I'm looking for an easy way to have unobtrusive client-side validation for a List
with the [Required]
attribute.
Edit: I just realized the [Required] attribute will probably only verify that Function
is not null
. It will not check if it contains any items. This is fine by me, as the property will become null automatically on postback.