Databases Reference
In-Depth Information
Due to the power and inherent complexity of regular expressions, it is a good idea to
invest more effort in testing them. In particular, you might want to write both positive
and negative tests to ensure not only that your regular expression rejects invalid values,
but also that it accepts the valid ones:
[TestMethod]
public void HomePage_AcceptsValidUrl()
{
using (new TransactionScope())
using (var context = new NorthwindEntities())
{
var supplier = new Supplier();
supplier.CompanyName = “Test Supplier”;
supplier.HomePage = “http://www.contoso.com”;
context.Suppliers.AddObject(supplier);
context.SaveChanges();
}
}
[TestMethod]
[ExpectedValidationException(MemberName = “HomePage”)]
public void HomePage_RejectsInvalidUrl()
{
using (new TransactionScope())
using (var context = new NorthwindEntities())
{
var supplier = new Supplier();
supplier.CompanyName = “Test Supplier”;
supplier.HomePage = “invalid://url”;
context.Suppliers.AddObject(supplier);
context.SaveChanges();
}
}
Unlike with most other validation attributes that manage to generate reasonably good
error messages by default, the RegularExpressionAttribute cannot decipher the original
intent and simply includes the entire regular expression pattern in the error message. You
definitely don't want to display those error messages to the business users. As discussed in
the Va l i d a t i o n E r ro r M e s s a g e s section of this chapter, you can specify an alternative error
message by setting the ErrorMessage property in the attribute constructor, for example:
[RegularExpression(
@”(?i)(http | https)://[a-z0-9\-\.]+\.(com | org | net | mil | edu)”,
ErrorMessage = “Home Page must be a valid URL” )]
public object HomePage { get; set; }
 
Search WWH ::




Custom Search