How to validate an IEnumerable property using DataAnnotations?

0
I want to validate this IEnumerable<long> selectedItems using select to check if it is empty because it needs to at least have a selected value. I have a IEnumerable it's to display a DataAnnotations to select multiple values. I'm trying to use Required but it's not working. How can I do this?

I'm trying like this.

Model

public class EmpresaModel{
    [Required(ErrorMessage = "Selecione ao menos uma forma de pagamento disponível")]
    public IEnumerable<long> selectedItems { get; set; }
}

HTML

<div class="form-group">
    <label for="@Html.IdFor(model => model.selectedItems)" class="cols-sm-2 control-label">Formas de pagamento disponíveis <img src="~/Imagens/required.png" height="6" width="6"></label>
    @Html.ListBoxFor(model => model.selectedItems, Model.formasPagto, new { Class = "form-control", placeholder = "Selecione as formas de pagamento disponíveis", @multiple = true})
    @Html.ValidationMessageFor(model => model.formasPagto)
</div>
    
asked by anonymous 21.10.2016 / 21:54

1 answer

0

You have an HTML error in ValidationMessageFor should look like this:

@Html.ValidationMessageFor(model => model.selectedItems)

and the value that was formasPagto was wrong.

Full Html:

@using (Html.BeginForm("Store", "Home", FormMethod.Post))
{
    <div class="form-group">
        <label for="@Html.IdFor(model => model.selectedItems)" class="cols-sm-2 control-label">Formas de pagamento disponíveis<img src= "~/Imagens/required.png" height= "6" width= "6" ></label>
        @Html.ListBoxFor(model => model.selectedItems, new List<SelectListItem> { new SelectListItem() { Value = "1", Text = "1" }, new SelectListItem() { Value = "2", Text = "2" } }, new { Class = "form-control", placeholder = "Selecione as formas de pagamento disponíveis" })
        @Html.ValidationMessageFor(model => model.selectedItems)
    </div>
    <button>Enviar</button>
}

The validation that you put is correct is Required even what was missing I believe to be JQuery and its complements for validation:

  

<script src="/Scripts/jquery-1.10.2.js"></script>

     

<script src="/Scripts/jquery.validate.js"></script>

     

<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

You have a file that is best to set this in the App_Start folder in the BundleConfig file, make a change like this:

namespace WebApp
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js", 
                        "~/Scripts/jquery.validate*"));

that is, by adding "~/Scripts/jquery.validate*" to do the first validation on the client side.

    
21.10.2016 / 22:24