Current project:
- ASP.NET 4.5.1
- MVC 5
I need to know if I can nest When() statements like this:
When(x => x.Cond1 == val1,
() => {
When(x => x.SubCond1 == SubVal1,
() => {
When(x => x.Final1 == finalVal1,
() => {
RuleFor(x => x.Field1)
.NotEmpty().WithMessage("Should not be empty");
// a few more here
});
When(x => x.Final2 == finalVal2,
() => {
RuleFor(x => x.Field8)
.NotEmpty().WithMessage("Should not be empty");
// a few more here
});
});
When(x => x.SubCond2 == SubVal2,
() => {
RuleFor(x => x.Field16)
.NotEmpty().WithMessage("Should not be empty");
// a few more here
});
});
Because the last thing I want is to decorate 30+ form fields like this:
RuleFor(x => x.Field1)
.NotEmpty().WithMessage("Should not be empty")
.When(x => x.Cond1 == val)
.When(x => x.SubCond1 == SubVal1)
.When(x => x.Final1 == finalVal1);
That is just untenable.
None of the conditions require validation themselves, as none of them are actually user-editable fields (just user-selectable values); I just need to compare them against known values. I would use an if/else statement if that was actually more appropriate, which it isn’t.
The model is largely flat, with only the second-level When() representing an imported model, and the third-level being different ways to handle specific fields within the imported model.
You can't, but you can try and use Rule Sets to group your rules together. Also maybe check Cascade Mode.