Search code examples
entity-frameworkvalidationasp.net-coremulti-selecttag-helpers

I have a Multiselect list on ASP.net Core and validaton is not woking


I have a select field

<select asp-for="UserCitizenships" asp-items="Model.CitizenshipsList" class="select2 required">

that is populated by a multiselect list

public MultiSelectList CitizenshipsList { get; set; }

And returns a List of Int

 public List<int> UserCitizenships

that I handle manually in the backend. Validation from Data Annotations is not working. I need at least one property to be populated when the form submits. Any ideas?

  [Required(ErrorMessage = Helpers.ErrorMessages.Required)]
    public List<int> UserCitizenships
    {
        get
        {
           ....

Solution

  • I would have thought the following would work

    [Required, MinLength(1, ErrorMessage = "At least one item required")]
    public List<int> UserCitizenships { get; set; }
    

    Alternatively you could create a custom data annotation or use class level validation

    public class YourClass : IValidatableObject
    {
        [Required]
        List<int> UserCitizenships
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (UserCitizenships.Count < 1)
            {
                yield return new ValidationResult(
                    $"At least one UserCitizenship should be specified.",
                    new[] { nameof(UserCitizenships) });
            }
        }   
    }