Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation passing parameter

I've found FluentValidation only couple of hours ago and I want to rewrite all my validation logic so it will use only FV.

The issue that I have ATM is that I would like to use data coming from input as a parameter for DomainExists() method. Is it possible or do I have to figure out a way around FV to achieve that?

    public QuoteValidator()
    {
    // hardcoded because don't know how to pass input string to RuleFor
        var inputeddomain = "http://google.com";

        RuleFor(r => r.Domain).NotEqual(DomainExists(inputeddomain));
    }

    // checks if inputeddomain is in repository (SQL DB)
    private string DomainExists(string inputeddomain)
    {
        var context = new QuoteDBContext().Quotes;
        var output = (from v in context
                     where v.Domain == inputeddomain
                     select v.Domain).FirstOrDefault();

        if (output != null) { return output; } else { return "Not found"; }
    }

Thanks to @bpruitt-goddard hint I got that to work. Here's a solution to my problem (hope it will help somebody).

        public QuoteValidator()
    {
        RuleFor(r => r.Domain).Must(DomainExists).WithMessage("{PropertyValue} exists in system!");
    }

    private bool DomainExists(string propertyname)
    {
        var context = new QuoteDBContext().Quotes;
        var output = (from v in context
                      where v.Domain == propertyname
                      select v.Domain).FirstOrDefault();

        if (output != null) { return false; } else { return true; }
    }
like image 288
Chris Hermut Avatar asked Aug 14 '14 15:08

Chris Hermut


1 Answers

You can use FluentValidation's Must method to pass in extra data from the input object.

RuleFor(r => r.Domain)
  .Must((obj, domain) => DomainExists(obj.InputDomain))
  .WithErrorCode("MustExist")
  .WithMessage("InputDomain must exist");

Although this will work, it is not recommended to check for database existence in the validation layer as this is verification versus validation. Instead, this kind of check should be done in the business layer.

like image 151
bpruitt-goddard Avatar answered Sep 24 '22 00:09

bpruitt-goddard