FluentValidation rule for null object

后端 未结 9 1145
遥遥无期
遥遥无期 2020-12-25 10:44

I\'ve been trying to work out how to create a FluentValidation rule that checks if the instance of an object it\'s validating is not null, prior to validating it\'s properti

9条回答
  •  情话喂你
    2020-12-25 11:28

    This is an older post, but want to update the answers to include the following from the FluentValidation documentation:

    Using PreValidate

    If you need to run specific code every time a validator is invoked, you can do this by overriding the PreValidate method. This method takes a ValidationContext as well as a ValidationResult, which you can use to customise the validation process.

    public class MyValidator : AbstractValidator {
      public MyValidator() {
        RuleFor(x => x.Name).NotNull();
      }
    
      protected override bool PreValidate(ValidationContext context, ValidationResult result) {
        if (context.InstanceToValidate == null) {
          result.Errors.Add(new ValidationFailure("", "Please ensure a model was supplied."));
          return false;
        }
        return true;
      }
    }
    

    https://fluentvalidation.net/start#using-prevalidate

提交回复
热议问题