GidiBloke
GidiBloke

Reputation: 488

NotEmpty Validation for Multiple Fields

I have a form with some NotEmpty fields. Now i can always write a rule for each field and write the same message for each. I was hoping there is a better way to write it. Maybe write it in one line and list all off the fields.

I have tried the code below but it doesn't seem to work.I am not even sure if this is close to the answer. I have searched everywhere but i can't seem to find an example. I have also looked at the documentation, no luck. Sorry if the answer is obvious, it has been doing my head in for the past hour.

RuleFor(x => new { x.FirstField, x.SecondField, x.ThirdField, x.FourthField }).NotEmpty().WithMessage("Field cannot be null");

Upvotes: 0

Views: 116

Answers (1)

smolchanovsky
smolchanovsky

Reputation: 1863

The library does not allow this. But as Roman said, you can write an extension, like so:

public class MyAbstractValidator<T> : AbstractValidator<T>
{
    public IEnumerable<IRuleBuilderInitial<T, TProperty>> RuleForParams<TProperty>(params Expression<Func<T, TProperty>>[] expressions)
    {
        return expressions.Select(RuleFor);
    }
}

public static class RuleBuilderInitialExtensions
{
    public static void ApplyForEach<T, TProperty>(this IEnumerable<IRuleBuilderInitial<T, TProperty>> ruleBuilders, Action<IRuleBuilderInitial<T, TProperty>> action)
    {
        foreach (var ruleBuilder in ruleBuilders)
        {
            action(ruleBuilder);
        }
    }
}

public class CustomerValidator : MyAbstractValidator<Customer>
{
    public CustomerValidator()
    {
        RuleForParams(x => x.FirstField, x => x.SecondField, x => x.ThirdField).ApplyForEach(x => x.NotEmpty().WithMessage("Field cannot be null"));
    }
}

Upvotes: 1

Related Questions