首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >FluentValidation仅在值不为空时应用规则

FluentValidation仅在值不为空时应用规则
EN

Stack Overflow用户
提问于 2019-05-16 05:15:59
回答 2查看 3.7K关注 0票数 1

对于FluentValidation,我有以下扩展方法

代码语言:javascript
运行
复制
    public static IRuleBuilderOptions<T, string> MustHasLengthBetween<T>(this IRuleBuilder<T, string> rule, int min, int max)
    {
        return rule
            .Length(min, max).WithMessage(someCustomMessage);
    }

只有当属性上有某些内容时,如果它是nullempty字符串,则不应该验证此规则,我希望应用此规则。

在调用验证类中,我可以这样做:

代码语言:javascript
运行
复制
        RuleFor(a => a.SomeProperty)
            .MustHasLengthBetween(5, 10)
            .When(x => !String.IsNullOrEmpty(x.SomeProperty))

它可以工作,但是我必须将这个When调用放在每个调用方法上。是否有任何方法将When调用移动到扩展方法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-16 06:38:34

在下面添加扩展When构建器可以让您访问属性值。您也可以在其他验证中重复使用此方法。

代码语言:javascript
运行
复制
public static IRuleBuilderOptions<T, TProperty> When<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, TProperty, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators)
{
    return rule.Configure(config => {
        config.ApplyCondition(ctx => predicate((T)ctx.Instance, (TProperty)ctx.PropertyValue), applyConditionTo);
    });
}

测试

代码语言:javascript
运行
复制
public class UnitTest1
{
    [Fact]
    public void Should_validate_length ()
    {
        var ok1 = new Model { MyProperty = null };
        var ok2 = new Model { MyProperty = "" };
        var ok3 = new Model { MyProperty = "55555" };
        var fail = new Model { MyProperty = "1" };

        var v = new ModelValidator ();

        v.ValidateAndThrow (ok1);
        v.ValidateAndThrow (ok2);
        v.ValidateAndThrow (ok3);

        Should.Throw<ValidationException> (() => v.ValidateAndThrow (fail));
    }

    public class Model
    {
        public string MyProperty { get; set; }
    }

    public class ModelValidator : AbstractValidator<Model>
    {
        public ModelValidator ()
        {
            RuleFor (x => x.MyProperty)
                .MustHaveLengthBetween (5, 10);
        }
    }
}

public static class Extensions
{
    public static IRuleBuilderOptions<T, string> MustHaveLengthBetween<T> (this IRuleBuilder<T, string> rule, int min, int max)
    {
        return rule
            .Length (min, max).WithMessage ("AGAGA")
            .When ((model, prop) => !string.IsNullOrEmpty (prop));
    }

    /// <summary>
    /// Predicate builder which makes the validated property available
    /// </summary>
    /// <param name="IRuleBuilderOptions<T"></param>
    /// <param name="rule"></param>
    /// <param name="predicate"></param>
    /// <param name="applyConditionTo"></param>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="TProperty"></typeparam>
    /// <returns></returns>
    public static IRuleBuilderOptions<T, TProperty> When<T, TProperty> (this IRuleBuilderOptions<T, TProperty> rule, Func<T, TProperty, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators)
    {
        return rule.Configure (config =>
        {
            config.ApplyCondition (ctx => predicate ((T) ctx.Instance, (TProperty) ctx.PropertyValue), applyConditionTo);
        });
    }
}
票数 2
EN

Stack Overflow用户

发布于 2019-05-16 07:33:41

代码语言:javascript
运行
复制
public static IRuleBuilderInitial<T, string> MustHasLengthBetween<T>(this IRuleBuilder<T, string> rule, int min, int max)
        {
            return rule.Custom((obj, context) =>
            {
                if (!String.IsNullOrEmpty(obj) && (obj.Length < min || obj.Length > max))
                {
                    context.AddFailure("custom message");
                }
            });
        }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56161263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档