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();
        engine.For<Person>()
                .Setup(m => m.Name)
                    .MustNotBeNullOrEmpty()
                    .WithMessage("Name must not be empty") //Only when name is null or empty
                    .MustMatchRegex(@"^[a-z]+$")
                    .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.
                    .MustNotBeNullOrEmpty()
                    .MustMatchRegex(@"^[a-z]+@[a-z]+(\.[a-z]+)*$");

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

        var member = new Member() { Email = "bill@hotmail.com", 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 5:51 AM by athoma13, version 3

Comments

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

sedi Aug 5, 2015 at 7: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 9:14 PM 
One thing to also note about the WithMessage feature is that if you have the following rule

engine.For<Member>()
.Setup(m => m.MaxCharactersInName)
.MustBeLessThan(50);
.WithMessage("Your name must be less than {0} characters");

This will return this message:

"Your name must be less than 50 characters"