在FluentValidation中动态返回所需属性的名称

时间:2015-08-20 15:50:49

标签: asp.net-mvc fluentvalidation

我制定了一条规则,如果分类是' IT'或者'部分',用户名或描述不得为空或空白'。

但是因为我不是依赖字符串文字来返回必填字段的名称而是强烈地输入它们,所以我使用了Ilya Ivanov的Using FluentValidation's WithMessage method with a list of named parameters答案。 (我知道我不得不用一种有趣的方式来说明这一点。)

我现在最感兴趣的是两件事:

答:是否应该更大的凝聚力'在SomeUserInformationMustNotBeEmpty和CreateErrorMessage之间?现在,我可能会意外地在另一个属性上进行验证,然后忘记将其添加到消息中(反之亦然)?

B:错误消息是否可以从验证本身动态生成(显然,对于甚至不需要WithMessage的简单规则来说就是这种情况)?

所以我的问题是:有没有办法使用Custom Property Validator或类似的东西验证返回错误消息,具体取决于传递的属性为&#39所需' (即!String.IsNullorEmpty(property))?

也许像

RuleFor(d => d.Category)
              .MustEnforceAtLeastOneNonEmpty(ListOfProperties)
              .When(x => x.Category.IsIn(Category.Part, Category.IT))

将根据当前规则验证并返回消息:

"You need to enter a Username or Description when the category is IT" 

并且,如果我添加'年龄'要到所需的属性列表,它将验证并返回消息:

"You need to enter a Username, Age or Description when the category is IT"

或者甚至可能:

"You need to enter a Username, Age or Description when the category is IT or Part"

我当前的视图模型:

[Validator(typeof(LeaveRequestValidator))]
public class LeaveRequestModel
{
    public string Username { get; set; }

    public Category Category { get; set; }

    public string Description { get; set; }

    public int Age { get; set; }
}

类别是枚举:

public enum Category
{
    HR = 1,
    Finance = 2,
    Part = 3,
    IT = 4
}


public class LeaveRequestValidator : AbstractValidator<LeaveRequestModel>
{
    public LeaveRequestValidator()
    {

        // Option One. A single line and a private bool. 
        RuleFor(d => d)
                       .Must(SomeUserInformationMustNotBeEmpty)
                       .When(x => x.Category.IsIn(Category.Part, Category.IT))
                       .WithMessage("{0}", CreateErrorMessage);


    private bool SomeUserInformationMustNotBeEmpty(LeaveRequestModel leaveRequestModel)
    {
        return (!String.IsNullOrEmpty(leaveRequestModel.Username) || !String.IsNullOrEmpty(leaveRequestModel.Description));
    }

    private string CreateErrorMessage(LeaveRequestModel leaveRequestModel)
    {
        string requiredPropertyOne = ModelMetadata.FromLambdaExpression<LeaveRequestModel, string>(x => x.Username, new ViewDataDictionary<LeaveRequestModel>()).DisplayName;
        string requiredPropertyTwo = ModelMetadata.FromLambdaExpression<LeaveRequestModel, string>(x => x.Description, new ViewDataDictionary<LeaveRequestModel>()).DisplayName;
        string checkedPropertyTwo = LeaveRequestModel.Category.GetType().Name.ToString();
        return String.Format("You need to enter a {0} or {1} when the {2} is {3}.", requiredPropertyOne, requiredPropertyTwo, checkedPropertyTwo, LeaveRequestModel.Category);
    }
}

我使用了一个小扩展来搜索Category的枚举。

public static class Extensions
{
    public static bool IsIn<T>(this T value, params T[] list)
    {
        return list.Contains(value);
    }
}

0 个答案:

没有答案