SajithK
SajithK

Reputation: 1032

Validating enums with FluentValidation

I'm using FluentValidation.WebApi 6.2.1.0 in Web API project. Is there a way to validate enum with FluentValidation and return custom message?

my controller action is as following,

public IHttpActionResult Get([FromUri]CheckUpdateVM info)
{
    ...
}

My Model,

[Validator(typeof(CheckUpdateVMValidator))]
public class CheckUpdateVM
{
    public DeviceTypes Device { get; set; }
}

I'm looing for something like this,

public class CheckUpdateVMValidator : AbstractValidator<CheckUpdateVM>
{
    public CheckUpdateVMValidator()
    {
        RuleFor(x => x.Device).Must(x => Enum.IsDefined(typeof(DeviceTypes), x)).WithMessage("xxx");
    }
}

With above code, Model binder validate the value of "Device" parameter and response with an error. but I can't customize the error message. (If I set the "Device" property type to string, this works fine.)

Upvotes: 1

Views: 6641

Answers (1)

laszczm
laszczm

Reputation: 173

Creating custom validator could be better approach in this scenario.

public class DeviceEnumValidator<T> : PropertyValidator {

public DeviceEnumValidator() 
    : base("Invalid Enum value!") { }

protected override bool IsValid(PropertyValidatorContext context) { 

    DeviceTypes enumVal= (DeviceTypes) Enum.Parse(typeof(DeviceTypes), context.PropertyValue);

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

    return true;
 }
}

To use DeviceEnumValidator you can call SetValidator when defining a validation rule.

public CheckUpdateVMValidator()
{
    RuleFor(x => x.Device).SetValidator(new DeviceEnumValidator<DeviceTypes>());
}

Upvotes: 2

Related Questions