How can I validate an enum using FluentValidator?

2

I am creating a validation class in c# using FluentValidation to validate that my Type property of my Account class is of type AccountType which is my enum .

How would the correct implementation of this be?

 RuleFor (account => account.Type)
             .IsInEnum (....)
    
asked by anonymous 06.01.2017 / 19:12

1 answer

1

You've come very close to the solution, you can use Must to check the type of your fields or move them with others fields or in your case with a enum ,

To know if the type of a field is equal to a particular type you first need to capture the type of the field with GetType() .

RuleFor(x => x).Must(p => p.Type.GetType().IsEnum);

IsEnum , already does the check you need, Fluent Validation has an error condition to be triggered when the result is TRUE , so if you want an error to be thrown when your property is different from IsEnum then use a denial.

RuleFor(x => x).Must(p => !p.Type.GetType().IsEnum);

For a check in a client class it would look like this.

using FluentValidation;
using System;

namespace TesteDryIoC.Generic.Validacoes
{
    public class ClienteValidator : AbstractValidator<Cliente>
    {
        public ClienteValidator()
        {
            RuleFor(x => x).Must(p => p.Type == MeusEnuns.Numero);
            RuleFor(x => x).Must(p => p.Type.GetType().IsEnum);
        }
    }
}

In RoleFor , I'm accessing my client class and passing all its properties to Must, you can do several checks like this or even call a more robust method returning a bool with the result of the validation.     

27.09.2017 / 14:25