Friday, May 7, 2010

Creating Csla Attribute Based E-mail Validator

With Csla 3.8, you can now use the System.ComponentModel.DataAnnotations feature set to write business validation rules.

One of the neat features of the Csla implementation is that it will work with the normal System.ComponentModel.DataAnnotations feature set in technologies that support it, as well as, provide a secondary validation with the Csla validation engine.

For example, this is a Csla property that contains all of the necessary validation:
private static PropertyInfo NameProperty = RegisterProperty(c => c.Name);

[Required, RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")]
public string Email
{
get { return GetProperty(NameProperty); }
set { SetProperty(NameProperty, value); }
}

Here we are validating that the Email property matches the validation regular expression, which works.... but what if you want to create your own attribute based validations.

Well,the ValidationAttribute(s) contained within the System.ComponentModel.DataAnnotations support an inheritance model, and you can design your own. For example a common e-mail validation:
public class EmailValidation : RegularExpressionAttribute
{
public EmailValidation()
: base(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")
{}

public override bool IsValid(object value)
{

return base.IsValid(value);
}
}

This can then be used as an attribute validation on your property:
private static PropertyInfo NameProperty = RegisterProperty(c => c.Name);
[Required, EmailValidation]
public string Name
{
get { return GetProperty(NameProperty); }
set { SetProperty(NameProperty, value); }
}

Resources:
Csla
System.ComponentModel.DataAnnotations

No comments: