Skip to content

Commit c27221c

Browse files
committed
Documentation for Include rules
1 parent c9ee3bb commit c27221c

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

docs/_doc/start.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,6 @@ sections:
1414
- /start/collections
1515
- /start/complex-properties
1616
- /start/rulesets
17+
- /start/including-rules
1718
- /start/configuring
1819
---

docs/_doc/start/including-rules.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
---
2+
title: Including Rules
3+
---
4+
You can include rules from other validators provided they validate the same type. This allows you to split rules across multiple classes and compose them together (in a similar way to how other languages support traits). For example, imagine you have 2 validators that validate different aspects of a `Person`:
5+
6+
```csharp
7+
public class PersonAgeValidator : AbstractValidator<Person> {
8+
public PersonAgeValidator() {
9+
RuleFor(x => x.DateOfBirth).Must(BeOver18);
10+
}
11+
12+
protected bool BeOver18(DateTime date) {
13+
//...
14+
}
15+
}
16+
17+
public class PersonNameValidator : AbstractValidator<Person> {
18+
public PersonNameValidator() {
19+
RuleFor(x => x.Surname).NotNull().Length(0, 255);
20+
RuleFor(x => x.Forename).NotNull().Length(0, 255);
21+
}
22+
}
23+
```
24+
25+
Because both of these validators are targetting the same model type (`Person`), you can combine them using `Include`:
26+
27+
```csharp
28+
public class PersonValidator : AbstractValidator<Person> {
29+
public PersonValidator() {
30+
Include(new PersonAgeValidator());
31+
Include(new PersonNameValidator());
32+
}
33+
}
34+
```
35+
36+
*Note*: You can only include validators that target the same type as the root validator.

0 commit comments

Comments
 (0)