简体   繁体   中英

fluentvalidation: apply globally for all string properties

I want to validate all string properties globally, so that they do not start with "=" character.

Is there a way to implement a validation globally for all string properties using FluentValidator.

I have gone thru the documentation but I am not able to find any way to do it!

I think if such opportunity exists they would mentioned it in the documentation, but as you can see they don't. On my mind adding a tool like that is not a good idea because sharing validation rules between all the validator instances which have a specific type can lead to unexpected validation results. That also means that you have to make a tool which can exclude specific Validators from global context. So compare editing a single.cs file with your validator for concrete type not beeing scared of broking validation logic for others to using such thing that makes your code less reliable, more difficult to understand and mentain. Is it still woth it?

But if you sure that you can share validation rules between validators, than you can use base class for storing those rules (as you mentioned in comments).

Example:

public class Parent
{
    public string ParentValue1 { get; set; }

    public string ParentValue2 { get; set; }
}

public class Child : Parent
{
}  

And validators:

public class ParentValidator : AbstractValidator<Parent>
{
    public ParentValidator()
    {
        RuleFor(x => x.ParentValue1).NotEmpty();
        RuleFor(x => x.ParentValue2).NotEmpty();
    }
}

public class ChildValidator : AbstractValidator<Child>
{
    public ChildValidator()
    {
        Include(new ParentValidator());
    }
}

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