空对象的FluentValidation规则 [英] FluentValidation rule for null object

查看:138
本文介绍了空对象的FluentValidation规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试找出如何创建FluentValidation规则,以在验证其属性之前检查其正在验证的对象的实例是否不为null.

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 properties.

我宁愿将此null验证封装在Validator中,而不是在调用代码中进行.

I'd rather encapsulate this null validation in the Validator rather then doing it in the calling code.

请参见下面的示例代码,并在其中注释所需的逻辑:

See example code below with comments where the required logic is needed:

namespace MyNamespace
{
    using FluentValidation;

    public class Customer
    {
        public string Surname { get; set; }
    }

    public class CustomerValidator: AbstractValidator<Customer> 
    {
        public CustomerValidator() 
        {
            // Rule to check the customer instance is not null.

            // Don't continue validating.

            RuleFor(c => c.Surname).NotEmpty();
        }
    }

    public class MyClass
    {
        public void DoCustomerWork(int id)
        {
            var customer = GetCustomer(id);
            var validator = new CustomerValidator();

            var results = validator.Validate(customer);

            var validationSucceeded = results.IsValid;
        }

        public Customer GetCustomer(int id)
        {
            return null;
        }
    }
}

所以我的问题是我如何在CustomerValidator()构造函数中检查客户的当前实例不为空,并且如果该实例为空,则中止进一步的规则处理?

So my question is how do I check in the CustomerValidator() constructor that the current instance of customer is not null and abort further rule processing if it is null?

谢谢.

推荐答案

您应该能够覆盖CustomerValidator类中的Validate方法.

You should be able to override the Validate method in your CustomerValidator class.

public class CustomerValidator: AbstractValidator<Customer> 
{
    // constructor...

    public override ValidationResult Validate(Customer instance)
    {
        return instance == null 
            ? new ValidationResult(new [] { new ValidationFailure("Customer", "Customer cannot be null") }) 
            : base.Validate(instance);
    }
}

这篇关于空对象的FluentValidation规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆