0

The solutions I sought out do not solve my problem. I wrote a custom validator to force user to fill a field depending on a enum value selected from a dropdown. But the error message does not display when the required field is empty. When the select is Farmer (enum field) Outreach Person must be selected from dropdown (OutreachPersonId).

Custom Validator

    public class RequiredOutreachOfficerAttribute : ValidationAttribute
    {
        private CardTypes _cardTypes;

        public RequiredOutreachOfficerAttribute(CardTypes cardTypes)
        {
            _cardTypes = cardTypes;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            CreateBusinessPartnerVM businessPartner = (CreateBusinessPartnerVM)validationContext.ObjectInstance;

            if (businessPartner.CardType == _cardTypes && !businessPartner.OutreachPersonId.HasValue)
            {
                return new ValidationResult("A farmer must have an outreach officer");
            }

        return ValidationResult.Success;
    }
}

Model

[RequiredOutreachOfficer(CardTypes.Farmer, ErrorMessage = "A farmer must have an outreach officer")]
public Guid? OutreachPersonId { get; set; }

View

<label asp-for="OutreachPersonId">Outreach Officer</label>
@Html.DropDownListFor(m => m.OutreachPersonId, Model.OutreachPersons, "", new { @id = "drpOutreachPersonId", @class = "browser-default" })
 <span asp-validation-for="OutreachPersonId" class="text-danger"></span>

It seems that the custom validator works because when I select a "Farmer" enum from the dropdown, and I submit the page, it throws an exception;

InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'OutreachPersonId'.

But when I select another input that is not "Farmer" the page submits successfully. But I need the validation message to show. Please help.

Kacey Ezerioha
  • 1,068
  • 4
  • 22
  • 46
  • You do not get any client side validation because your attribute does not implement `IClientValidatable` and you have not included scripts to add the rules to the `$.validator`. Once you repopulate `OutreachPersons` as described in the dupe, your error message will be displayed –  Oct 19 '17 at 22:31
  • If you want client side validation, then 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) –  Oct 19 '17 at 22:32

0 Answers0