简体   繁体   中英

How can I can simple validators (not property specific) inside a fluent validator class?

I am using fluent validator for .net and it works great to validate the state of all of the properties of my objects like this:

RuleFor(h => h.Applications).NotEmpty().WithName("Applications");

RuleFor(h => h.OwnerId).GreaterThan(0).WithMessage("You need to choose a owner");

but i find myself adding additional validation logic in my Controller class (outside of my fluent validator class) adding in code like this below to jam in extra validation (that is not property specific)

 if (!Model.IsEntitledToEdit(project))
 {
    ModelState.AddModelError(string.Empty, "You are not entitled to save changes.");
}

is there any way to incorporate this type of validation inside a fluent validator class (so i can keep all of my validation in one place)

If you can get your method call in the form of a property, then you can do it.

For example:

RuleFor(h => h.CanEditFooProjects).Equals(true).WithMessage("You are not entitled to save changes.");

However, i'm guess code like this:

if (!Model.IsEntitledToEdit(project))

... is probably checking the authorization for editing 'project' objects.

You could wrap the business logic in the properties getter...

public bool CanEditFooProjects {
    get { 
        if( {some condition}) 
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

... then you could have the FluentValidation rule simply defined in one place.

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