docs/error-codes.md
A custom error code can also be associated with validation rules by calling the WithErrorCode method:
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(person => person.Surname).NotNull().WithErrorCode("ERR1234");
RuleFor(person => person.Forename).NotNull();
}
}
The resulting error code can be obtained from the ErrorCode property on the ValidationFailure:
var validator = new PersonValidator();
var result = validator.Validate(new Person());
foreach (var failure in result.Errors)
{
Console.WriteLine($"Property: {failure.PropertyName} Error Code: {failure.ErrorCode}");
}
The output would be:
Property: Surname Error Code: ERR1234
Property: Forename Error Code: NotNullValidator
The ErrorCode is also used to determine the default error message for a particular validator. At a high level:
NotNull() validator has a default error code of NotNullValidator, which used to look up the error messages from the LanguageManager. See the documentation on localization.ErrorCode can also be used to override the default error message. For example, if you use a custom Must() validator, but you'd like to reuse the NotNull() validator's default error message, you can call WithErrorCode("NotNullValidator") to achieve this result.