Search code examples
asp.net-mvcvalidationasp.net-corefluentvalidation

How to create a rule for several fields at the same time using FluentValidation


I need to validate the following situation in an Asp.net MVC project: If the fields ServicoEmail, ServicoWebsite, ServicoBlog, ServicoRedeSocial and ServicoMensagemInstantanea are all false, return an error message. I tried to do as below, but it is not working ... Does anyone know how to help me?

RuleFor(ps => new { ps.ServicoEmail, ps.ServicoWebsite, ps.ServicoBlog, ps.ServicoRedeSocial, ps.ServicoMensagemInstantanea })
    .Must(ps=> ps.ServicoEmail == false && ps.ServicoWebsite == false && ps.ServicoBlog == false && ps.ServicoRedeSocial == false && ps.ServicoMensagemInstantanea == false)
    .WithMessage("É necessário selecionar pelo menos um Tipo de Serviço.");

My Class:

public abstract class ServicoWebCommand : Command
{
    public int Id { get; protected set; }

    public string Descricao { get; protected set; }

    public string FormatoCampo { get; protected set; }

    public bool ServicoEmail { get; protected set; }

    public bool ServicoWebsite { get; protected set; }

    public bool ServicoBlog { get; protected set; }

    public bool ServicoRedeSocial { get; protected set; }

    public bool ServicoMensagemInstantanea { get; protected set; }

    public bool PadraoSistema { get; protected set; }
}

Solution

  • You need to specify each of them individually or you can specify a custom validator.

    Way 1 :

    RuleFor(ps => ps).SetValidator(new ServicoValidator());
    

    and then write Validator implementation:

    public class ServicoValidator: AbstractValidator<ServicoWebCommand>
    {
        public ServicoValidator()
        {
            RuleFor(t => t).Custom(ValidateServico);
        }
    
    
        private void ValidateServico(ServicoWebCommand ps, CustomContext validationContext)
        {
            if(ps.ServicoEmail == false && 
               ps.ServicoWebsite == false && 
               ps.ServicoBlog == false && 
               ps.ServicoRedeSocial == false && 
               ps.ServicoMensagemInstantanea == false)
             {
               validationContext.AddFailure("É necessário selecionar pelo menos um Tipo de Serviço.");
             }
        }
    }
    

    Way 2:

    RuleFor(ps => ps).Must(ps => Validate(ps));
    

    and write the method to validate like:

    private bool Validate(ServicoWebCommand ps)
    {
        if(ps.ServicoEmail == false && 
           ps.ServicoWebsite == false && 
           ps.ServicoBlog == false && 
           ps.ServicoRedeSocial == false && 
           ps.ServicoMensagemInstantanea == false) 
            return false;
    
        return true;
    }