Custom and Conditional Rules
Build complex, conditional validation logic.
Custom and Conditional Rules is a free C# Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Beyond Built-In Validators
Real-world validation often needs custom logic: a value passing a domain check, or a rule that only applies under certain conditions. FluentValidation supports both with Must, When and custom validator types.
The Must Predicate
Must takes a predicate that returns true when the value is valid. It is the simplest way to express arbitrary logic inline.
RuleFor(c => c.Username)
.Must(name => !name.Contains(" "))
.WithMessage("Username cannot contain spaces.");Must With Access To The Whole Object
An overload of Must gives you the parent object plus the property value, enabling cross-property checks.
RuleFor(o => o.DiscountedPrice)
.Must((order, discounted) => discounted <= order.OriginalPrice)
.WithMessage("Discounted price cannot exceed original price.");Conditional Rules With When
When applies a rule only if a condition holds. Here, a shipping address is required only for physical orders.
RuleFor(o => o.ShippingAddress)
.NotEmpty()
.When(o => o.RequiresShipping);The Unless Modifier
Unless is the inverse of When: the rule runs unless the condition is true.
RuleFor(o => o.CouponCode)
.NotEmpty()
.Unless(o => o.IsGift);Grouping Conditions
Wrap several rules in a single When(...) block to share a condition cleanly across all of them.
When(o => o.RequiresShipping, () =>
{
RuleFor(o => o.ShippingAddress).NotEmpty();
RuleFor(o => o.PostalCode).NotEmpty();
});Async Custom Logic With MustAsync
When your check needs the database or an API, use MustAsync. Validate the model with ValidateAsync.
RuleFor(u => u.Email)
.MustAsync(async (email, cancellation) =>
!await _repository.EmailExistsAsync(email))
.WithMessage("Email is already registered.");Writing A Reusable Custom Validator
For logic you reuse across projects, write an extension method on IRuleBuilder. This turns custom rules into first-class, chainable validators.
public static class CustomValidators
{
public static IRuleBuilderOptions<T, string> ValidSlug<T>(
this IRuleBuilder<T, string> rule)
{
return rule.Matches("^[a-z0-9-]+$")
.WithMessage("Must be a lowercase slug.");
}
}Using The Custom Validator
Once defined, the extension chains like any built-in validator, keeping your validators expressive.
RuleFor(p => p.Slug).NotEmpty().ValidSlug();The Custom Method For Full Control
For complex results, Custom lets you add validation failures imperatively using a context.
RuleFor(o => o.Items).Custom((items, context) =>
{
if (items.Count == 0)
context.AddFailure("An order must contain at least one item.");
});Cascade Modes
By default all validators in a chain run even after one fails. Set CascadeMode.Stop to halt at the first failure, avoiding redundant or unsafe checks.
RuleFor(c => c.Email)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.EmailAddress();Quick Check
Test conditional and custom rules.
Recap
Custom and conditional rules make FluentValidation flexible: Must for inline predicates (with an overload exposing the whole object), When/Unless for conditions, grouped When blocks, MustAsync for I/O checks, reusable IRuleBuilder extensions, the imperative Custom method, and Cascade modes to control evaluation flow.
Frequently asked questions
Is the “Custom and Conditional Rules” lesson free?
Yes — the full text of “Custom and Conditional Rules” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Custom and Conditional Rules”?
Build complex, conditional validation logic. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Custom and Conditional Rules” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Data Annotation Validation
- FluentValidation Rules
- Custom and Conditional Rules
- Integrating Validation with APIs