0

I'm attempting client side validation of a list. I want at least one item to be in the list.

I'm using the solution found here: ViewModel validation for a List

The ValidationAttribute is being called, and it is returning false when the list is empty or null, but the form is still submitting.

Model:

public class ProductsViewModel
{
    UniformRepository repo;

    public ProductsViewModel()
    {
        repo = new UniformRepository();

        Products = new List<Product>();
        ProductToEdit = new Product();
        Divisions = repo.GetAllDivisions();
    }

    public List<Product> Products { get; set; }
    public Product ProductToEdit { get; set; }
    public Division SelectedDivision { get; set; }
    public List<SelectListItem> DropDownVendors { get; set; }

    public List<Division> Divisions { get; set; }

    [EnsureOneElement(ErrorMessage = "At least one vendor is required")]
    public List<string> Vendors { get; set; }
}

part of the View in question:

 <div class="row top-buffer">
        <div class="col-md-3 col-md-offset-1">
            @Html.LabelFor(model => model.Vendors, new { @class = "GridLabel" })
        </div>
        <div class="col-md-3">
            @(Html.Kendo().MultiSelectFor(model => model.Vendors)
                .BindTo(Model.DropDownVendors)
                .HtmlAttributes(new { @class = "form-control" }))
            @Html.ValidationMessageFor(model => model.Vendors, "", new { @class = "text-danger" })
        </div>
    </div>

ValidationAttribute

    public class EnsureOneElementAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var list = value as IList;
            if (list != null)
            {
                return list.Count > 0;
            }
            return false;
        }
    }

Thanks for any ideas.

CThin
  • 156
  • 1
  • 11
  • Your EnsureOneElementAttribute is server-side code that has no client-side equivalent, so the form gets submitted because there is nothing in the client to stop it. The reason out-of-the box attributes like Required work is because they produce client-side attributes like "data-val-required" that is understood and enforced client-side. You need to implement the corresponding client-side enforcement your self. See https://stackoverflow.com/questions/25762041/asp-net-mvc-client-side-validation-of-custom-attribute (among many others). – The Dread Pirate Stephen Jun 15 '17 at 20:26
  • Your attribute needs to implement `IClientValidatable` and you need to write scripts to add the rules to the `$.validator. Refer [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](https://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) –  Jun 16 '17 at 01:14

0 Answers0