Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Using SetCollectionValidator - Overriding/Adding RuleSet

$
0
0
I'm trying to reuse a validator within another validator. The subvalidator doesn't have any rulesets defined but the validator using it does. When I call the validator with a ruleset it will not result in no validation errors since it's looking for the ruleset. Is there a way to override this or add the "default" ruleset?

Here's an example of what I'm trying to do.
    public class AuthPlanEntry
    {
        public DateTime? StartDate {get ; set;}
        public DateTime? EndDate { get; set;}
    }

    public class AuthChange
    {
        public AuthChange() { }
        public string Comments { get; set; }
        public List<AuthPlanEntry> AuthPlanEntries { get; set; }
    }

    internal class AuthPlanEntryValidator : AbstractValidator<AuthPlanEntry>
    {
        internal AuthPlanEntryValidator()
        {
            RuleFor(x => x.StartDate)
                .NotNull()
                .GreaterThan(SqlDateTime.MinValue.Value).WithMessage("Invalid Date");

            RuleFor(x => x.EndDate)
                .NotNull()
                .GreaterThan(x => x.StartDate.Value).WithMessage("Invalid Date")
                .When(x => x.EndDate.HasValue && x.StartDate.HasValue);
        }
    }

    public class AuthChangeValidator : AbstractValidator<AuthChange>
    {
        public AuthChangeValidator()
        {
            RuleSet("MyRuleSet", () =>
            {
                RuleFor(x => x.AuthPlanEntries).SetCollectionValidator(new AuthPlanEntryValidator());

                RuleFor(x => x.Comments)
                    .Cascade(CascadeMode.StopOnFirstFailure)
                    .NotEmpty().WithMessage("Comments are required");
            });
        }
    }
If I call validate on an AuthChangeValidator with the ruleset it will pass even if the auth plan entries have invalid dates.

Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>