How can I validate an Enum using Fluentvalidator?

Asked

Viewed 404 times

2

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

How would the correct implementation of this?

 RuleFor (account => account.Type)
             .IsInEnum (....)

1 answer

1

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

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

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

The IsEnum, already does your checking you need, Fluent Validation has an error condition to be triggered when the result is TRUE, then if you want an error to be made 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 customer class 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 the RoleFor, i am accessing my customer class and passing to the Must all its properties, you can do various check like this or even call a more robust method by returning a bool with the result of the validation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.