FluentValidation validate Enum value

JaggenSWE picture JaggenSWE · Jul 10, 2017 · Viewed 17.8k times · Source

I have the following model:

public class ViewDataItem
{
    public string viewName { get; set; }
    public UpdateIndicator updateIndicator { get; set; }
}

With the following enum:

public enum UpdateIndicator
{
    Original,
    Update,
    Delete
}

And the following Validator:

public class ViewValidator : AbstractValidator<ViewDataItem>
{
    public ViewValidator()
    {
        RuleFor(x => x.viewName).NotEmpty().WithMessage("View name must be specified");
        RuleFor(x => x.updateIndicator).SetValidator(new UpdateIndicatorEnumValidator<UpdateIndicator>());
    }
}

public class UpdateIndicatorEnumValidator<T> : PropertyValidator
{
    public UpdateIndicatorEnumValidator() : base("Invalid update indicator") {}

    protected override bool IsValid(PropertyValidatorContext context)
    {
        UpdateIndicator enumVal = (UpdateIndicator)Enum.Parse(typeof(UpdateIndicator), context.PropertyValue.ToString());

        if (!Enum.IsDefined(typeof(UpdateIndicator), enumVal))
          return false;

        return true;
    }
}

The code is in a WebAPI that receives data via JSON, deserialize it to an object and then validates, but for some reason I can send whatever I please in the updateIndicator, so long as I don't put in an integer value larger than the max index in the enum (i.e 1,2 or 3 works fine, but 7 will generate an error).

How can I get this to validate the input of the data I receive to see if that value is actually in the Enum?

Answer

Stacked picture Stacked · Nov 1, 2017

Try the built-in IsInEnum()

RuleFor(x => x.updateIndicator).IsInEnum();

This checks if the provided enum value is within the range of your enum, if not, the validation will fail:

"'updateIndicator' has a range of values which does not include '7'."