0

I am new to Fluent Validation. I have 4 if conditions in which only one will execute and I want to use RuleFor for these conditions. If condition fails, error code and message should display. For my 4 conditions there is only one error code and error message.

How can I use 4 conditions in RuleFor() along with single ErrorCode() and WithMessage()

1 Answers1

2

WithErrorCode() and WithMessage() accepts strings, so you can just set simple string variables with the applicable details and pass the variable.

string myerror = "666";
string mymessage = "My Custom message";

RuleFor(person => myclass.Property1).NotNull().WithErrorCode(myerror).WithMessage(mymessage);        

RuleFor(person => myclass.Property2).NotNull().WithErrorCode(myerror).WithMessage(mymessage);        

RuleFor(person => myclass.Property3).NotNull().WithErrorCode(myerror).WithMessage(mymessage);        

RuleFor(person => myclass.Property4).NotNull().WithErrorCode(myerror).WithMessage(mymessage);   

You should consider if this make sense however, the purpose of validation is to enhance debugging the problem with the data, so the messages and error codes should be as specific as possible. This might be OK in your case, only you can judge this.

Edit: To answer your question below.

Fluent Validation offers two other methods which might be useful.

I think the dependencies is more what you are looking for. So then you can have something like this;

    RuleFor(person => myclass.Property1).NotNull().DependentRules(() => {
        RuleFor(person => myclass.Property2).NotNull().WithErrorCode(myerror).WithMessage(mymessage);    
        RuleFor(person => myclass.Property3).NotNull().WithErrorCode(myerror).WithMessage(mymessage);    
        RuleFor(person => myclass.Property4).NotNull().WithErrorCode(myerror).WithMessage(mymessage);    
}).WithErrorCode(myerror).WithMessage(mymessage);
    

And you can embed rule within rule, with rule etc. But this quickly becomes difficult to read and terrible to debug.

jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
  • I have written in this format only but lets suppose only 1 condition will be true and others should get skip and as output in valid.Errors, I want error. So Is it possible in above way? – Niteesh Joshi Apr 04 '21 at 09:18
  • 1
    you can have your custom checks this way and return if one condition fails https://stackoverflow.com/questions/20529085/fluentvalidation-rule-for-multiple-properties/20546097#20546097 – azharuddin irfani Apr 04 '21 at 09:36