简体   繁体   中英

Fluent validation and Must custom validation

I have a class and my validation looks like this:

    public ValidationResult Validate(CustomerType customerType)
    {
        CustomerType Validator validator = new CustomerTypeValidator();
        validator.RuleFor(x => x.Number).Must(BeUniqueNumber);

        return validator.Validate(customerType);
    }

    public bool BeUniqueNumber(int number)
    {
        //var result = repository.Get(x => x.Number == customerType.Number)
        //                       .Where(x => x.Id != customerType.Id)
        //                       .FirstOrDefault();

        //return result == null;
        return true;
    }

The CustomerTypeValidator is a basic validator class that validates string properties.

I also add a new rule to check if the number is unique in the db. I do it in this class because there's a reference to the repository. The validator class has no such reference.

The problem here is that the BeUniqueNumber method should have a CustomerType parameter. However when I do this, I get an error on the RuleFor line above because 'Must' needs an int as a parameter.

Is there a way around this?

Can you try this?

public ValidationResult Validate(CustomerType customerType)
{
    CustomerTypeValidator validator = new CustomerTypeValidator();
    validator.RuleFor(x => x).Must(HaveUniqueNumber);

    return validator.Validate(customerType);
}

public bool HaveUniqueNumber(CustomerType customerType)
{
    var result = repository.Get(x => x.Number == customerType.Number)
        .Where(x => x.Id != customerType.Id)
        .FirstOrDefault();

    return result == null;
    //return true;
}

You should also be able to do this:

public ValidationResult Validate(CustomerType customerType)
{
    CustomerTypeValidator validator = new CustomerTypeValidator();
    validator.RuleFor(x => x.Number).Must(BeUniqueNumber);

    return validator.Validate(customerType);
}

public bool BeUniqueNumber(CustomerType customerType, int number)
{
    var result = repository.Get(x => x.Number == number)
        .Where(x => x.Id != customerType.Id)
        .FirstOrDefault();

    return result == null;
    //return true;
}

"I also add a new rule to check if the number is unique in the db. I do it in this class because there's a reference to the repository."

Well, why can't you give your validator a reference to the repository too?

CustomerTypeValidator validator = new CustomerTypeValidator(repository);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM