Custom Validators

Creating your own Custom Validators is as easy as copy and paste.

1. Create Custom RuleValidator Class

public class EmailAddressValidator<T> : RuleValidator<T,string>
{
    private readonly string VALID_EMAIL_REGEX = @"([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})";

    public EmailAddressValidator()
    {
        //Define either a Message Store Name or a default Message
        //MessageStoreName = "MyCompanyValidationMessages";
       //Message = "{PropertyName} is an invalid e-mail address";
    }

    public override object[] Parameters
    {
        get { return new object[]{}; }
    }

    public override ValidationResult Validate(RuleValidatorContext<T, string> context, , SpecificationContainer specificationContainer)
    {
        if (context.PropertyValue == null)
        {
            return null;
        }
        else
        {
            Regex emailRegex = new Regex(VALID_EMAIL_REGEX);
            return Evaluate(emailRegex.IsMatch(context.PropertyValue), context);
        }
    }
}


2. Create Class for Extension Method to DSL

public static class EmailAddressValidatorExtensions
{
    //This Method Name will be the name of the Rule in the DSL
    public static ActionJoinBuilder<T, string> IsEmailAddress<T>(this IRuleBuilder<T, string> expression)
    {
        expression.RegisterValidator(new EmailAddressValidator<T>());
        return expression.JoinBuilder;
    }
}

Once you add the Namespace to your Extension Method, the Rule will show in the DSL.

MessageStore

Create your own or embed the message in the class.

Optional How to create and configure a new MessageStore

TODO: Document creating a Custom Message Store with the naming conventions

Last edited Apr 16, 2010 at 1:17 AM by TechnoAg, version 5

Comments

No comments yet.