Reputation: 11
Created this validation:
public ActivityValidator(IUserAccessor userAccessor)
{
var userId = userAccessor.GetUserIdFromAccessToken();
RuleSet("CompleteHappeningAsync", () =>
{
RuleFor(a => a.ActivityTypeId).IsHappening()
.WithState(x => new BadRequest("Aktivnost nije Događaj"))
.DependentRules(() =>
{
RuleFor(a => a.EndDate).LessThanOrEqualTo(DateTimeOffset.Now)
.WithState(x => new BadRequest("Događaj se još nije završio"))
.DependentRules(() =>
{
RuleFor(a => a.EndDate).GreaterThan(DateTimeOffset.Now.AddDays(-7))
.WithState(x => new BadRequest("Prošlo je nedelju dana od završetka Događaja"))
.DependentRules(() =>
{
RuleFor(a => a.User.Id).Equal(userId)
.WithState(x => new BadRequest("Ne možete završiti tuđi događaj"))
.DependentRules(() =>
{
RuleFor(a => a.HappeningMedias).Empty()
.WithState(x => new BadRequest("Već ste završili događaj"));
});
});
});
});
});
}
How can this be rewritten in recommended way by using When?
CascadeMode is used for rules chained for one property, so this can't be used here.
Recommended WAY - image taken from official site
Upvotes: 0
Views: 218
Reputation: 11
I have found better way, instead of using When. Set cfg.ValidatorOptions.DefaultClassLevelCascadeMode = CascadeMode.Stop in Startup.cs and then you can write rules in better way in "AND" manner:
RuleFor(a => a.ActivityTypeId).IsHappening();
RuleFor(a => a.EndDate).LessThanOrEqualTo(DateTimeOffset.Now)
.WithState(e => new BadRequest("Događaj se još nije završio"));
RuleFor(a => a.EndDate).GreaterThan(DateTimeOffset.Now.AddDays(-7))
.WithState(e => new BadRequest("Prošlo je nedelju dana od završetka Događaja"));
RuleFor(a => a.User.Id).Equal(userId)
.WithState(e => new BadRequest("Ne možete završiti tuđi događaj"));
RuleFor(a => a.HappeningMedias).Empty()
.WithState(e => new BadRequest("Već ste završili događaj"));
Upvotes: 1