In previous
posts I wrote about validation AOP-style, using Policy Injection or Depency Injection (Unity). I am a true believer that this form of validation is the way to go.
That said, what kind of validation do you really need?
User Input Validation is probably the first thing that pops up into your mind, and that is indeed an important one. But, in fact, validation can be applied to almost every layer. That’s why they call it a cross cutting concern and AOP makes sense.
That’s not what I mean. I am talking about using validators here. You probably know the available ASP.NET validators, like shown in above picture.
But you know what? Although User Input Validation is important, sooner or later the data will be persisted to a database. And if your database accepts varchar(10) only, then “Thunderbird” is not such a good idea to type.
In short, you are in need of a StringLengthValidator.
Of course you can create you own simple validation rules engine, but fortunately it is also an out-of-the-box validator of Microsoft’s validation block.
Difficult? Not at all, when following these simple steps:
- Download and install Microsoft Enterprise Library 5.0
- Create a project
- Add a reference to the assemblies “Enterprise Library Validation Application Block” and – not to forget – “System.ComponentModel.DataAnnotations”
- In your class, add the namespace: Microsoft.Practices.EnterpriseLibrary.Validation, et voilá
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using System;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
public class Customer
{
[StringLengthValidator(0, 10)]
public string CustomerName;
public Customer(string name)
{
this.CustomerName = name;
}
}
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer("Thunderbird");
Validator<Customer> validator = ValidationFactory.CreateValidator<Customer>();
ValidationResults results = validator.Validate(customer);
if (!results.IsValid)
{
foreach (ValidationResult result in results)
{
Console.WriteLine(result.Message);
}
}
}
} |
Comments