FluentValidation Call RuleSet and Common Rules

前端 未结 5 797
无人共我
无人共我 2021-02-08 04:24

I have the following class

public class ValidProjectHeader : AbstractValidator
    {
        public ValidProjectHeader()
        {         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-08 04:31

    In your Validator class create a method, that includes all "common" rules that need to be applied at all times. Now you can call this method

    • from your "create" RuleSet
    • from outside of the RuleSet

    Example

    public class MyEntityValidator : AbstractValidator
    {
        public MyEntityValidator()
        {
            RuleSet("Create", () =>
                {
                    RuleFor(x => x.Email).EmailAddress();
                    ExecuteCommonRules();
                });
    
            ExecuteCommonRules();
        }
    
        /// 
        /// Rules that should be applied at all times
        /// 
        private void ExecuteCommonRules()
        {
            RuleFor(x => x.Name).NotEmpty();
            RuleFor(x => x.City).NotEmpty();
        }
    }
    

    You define the RuleSet for an action in your controller

    [HttpPost]
    public ActionResult Create([CustomizeValidator(RuleSet = "Create")]  MyEntity model)
    

    This will insure that requests to action Create will be validated with the RuleSet Create. All other action will use the call to ExecuteCommonRules in controller.

提交回复
热议问题