Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation Multiple error messages for one property

i am validating input values with FluentValidation. i am using a method to validate value from database which return's integer value -1, -2 and -3 for different error messages on the base of value. how can i display error message according to the return value from method. i made a variable in class scope and set the return value and in next statement i tried comparison and try to display the message but i observe that next statement is executed before the updating value.

i want to display different error messages for one input value.

for example user input a negative value error message should be "negative values are not allowed", if user input a large value number then message should be "number is too long".

here is code ISValidAction is method which validates the input and set the variable returnvalue this method always returns true.

int returnvalue = 0;
RuleFor(r => r.action).Must(ISValidAction).WithMessage("Action does not exist in the system.").When(r => !String.IsNullOrEmpty(r.action));

RuleFor(r => returnvalue).Must(r => !(returnvalue != 1 && returnvalue != -2 && returnvalue != -3)).WithMessage("");//for -1
        RuleFor(r => returnvalue).Must(r => !(returnvalue != 1 && returnvalue != -1 && returnvalue != -3)).WithMessage("");//for -2
        RuleFor(r => returnvalue).Must(r => !(returnvalue != 1 && returnvalue != -1 && returnvalue != -2)).WithMessage("");// for -3
like image 789
Malik Rizwan Avatar asked Dec 11 '22 17:12

Malik Rizwan


1 Answers

i got the solution! for showing multiple errors against one value.

i just added error messages in PropertyValidatorContext

RuleFor(r => r.action).Must(ActionRateLimit).When(r => !String.IsNullOrEmpty(r.action));

this is call for validation using a function.

here is method.

private bool ActionRateLimit(LogActionInput obj, string actionName, PropertyValidatorContext context)
        {
        int result = 0;
        IRecognitionStoreService StoreService = new RecognitionStoreService();
        result = StoreService.ActionRateLimit(actionName, obj.userName);            
        if (result==1)
        {
           return true;
        }
        else if (result==0)
        {
            context.MessageFormatter.AppendArgument("ValidationMessage","Invalid action name or the user doesn't exists.");
        }
        else if(result==-1)
        {
            context.MessageFormatter.AppendArgument("ValidationMessage", "Action exceeds its rate limit. Please try again in a while.");
        }
        else if (result == -3)
        {
            context.MessageFormatter.AppendArgument("ValidationMessage", "This user has not completed the prequisite challenge. Action logging failed.");
        }
        return false;

        }

    }

it works fine.

like image 199
Malik Rizwan Avatar answered Dec 25 '22 22:12

Malik Rizwan