This project is read-only.
Error Messages

The following example shows how error messages can be defined for Rules and Properties. Error Messages defined on a base clase, or Interface will trickle down to inheritors (unless inheritors overwrite the error message by re-defining one on the derived property or class).

To use error messages in multi-language environments (e.g. An ASP.NET website), use

...WithMessage(() => GetMeTheResourceString())

syntax. The function will be evaluated when the error message is needed, and not when the error message is defined.

class MessagesExample
    public abstract class Person
        public string Name { get; set; }
        public string Email { get; set; }
    public class Member : Person
        public int MembershipNumber { get; set; }

    static void Main(string[] args)
        var engine = new Engine();
                .Setup(m => m.Name)
                    .WithMessage("Name must not be empty") //Only when name is null or empty
                    .WithMessage("Name contains invalid characters") //Only when name contains invalid characters

                .Setup(m => m.Email)
                    .WithMessage("Invalid email address") //For any rule breakers on the Email property.

        engine.For<Member>() //Member will inherit rules set for a Person.
                .Setup(m => m.MembershipNumber)
                    .WithMessage("Membership number is not valid")

        var member = new Member() { Email = "", MembershipNumber = 123, Name = "bill" };
        var report = new ValidationReport(engine);
        var result = report.Validate(member);
        var errors = report.GetErrorMessages(member);

Last edited Mar 25, 2012 at 6:51 AM by athoma13, version 3


terryterryd Jul 13, 2016 at 2:46 PM 
.WithMessage(string.Format("Your name length exceeds {0}.",m.MaxCharactersInName));

sedi Aug 5, 2015 at 8:31 AM 
Can I write the value being tested into the error message? Something like this:

.WithMessage("Your name length exceeds {m.MaxCharactersInName}.");

PRoe Feb 28, 2013 at 10:14 PM 
One thing to also note about the WithMessage feature is that if you have the following rule

.Setup(m => m.MaxCharactersInName)
.WithMessage("Your name must be less than {0} characters");

This will return this message:

"Your name must be less than 50 characters"