I had spent 2 weeks before Christmas to develop a small library to do the validation. It's a lot similar to FluentValidation in syntax. Actually, the implementation and fluent syntax are inspired from this well-known library Fluent Validation. However, I implemented it using Chain of Reponsibility pattern and made it support Dependency Injection for validator classes. Here is a simple example that can help you to start:
public class UserValidator : TypeValidator<User> { public UserValidator() { RuleFor(user => user.Id) .NotEmpty() .NotNull(); RuleFor(user => user.UserName) .NotNull() .Length(6, 10) .Must(x => !x.Contains(" ")).WithMessage("@PropertyName cannot contain empty string."); RuleFor(user => user.Password) .StopOnFirstError() .NotEmpty() .Length(6, 20) .Must(x => x.Any(c => c >= 'a' && c <= 'z') && x.Any(c => c >= '0' && c <= '9') && x.Any(c => c >= 'A' && c <= 'Z')).WithMessage("@PropertyName must contain both letter and digit."); RuleFor(user => user.Title) .In("MR", "MS", "MRS", "DR", "PROF", "REV", "OTHER"); RuleFor(user => user.FirstName) .NotEmpty().WithMessage("Please specify the first name."); RuleFor(user => user.LastName) .NotEmpty().WithMessage("Please specify the last name."); RuleFor(user => user.Email) .Email(); RuleFor(user => user.Address) .SetValidator<AddressValidator>() .When(x => x != null); } }I'm currently using this library for a heavy server side validation project and so far so good. You may ask me why don't I just use FluentValidation instead of reinventing the wheel? My answer is I want to keep myself busy. I have a passionate on Fluent interfaces for a while and this is a good opportunity for me to "do something" :D Anyway, the source code repository for this project is on GitHub. The NuGet package "NValidator" is also available. Please checkout the document and other topics to get started.
Happy New Year.
0 comments:
Post a Comment