Fluent Validation is a validation library for .NET. It uses a fluent interface and lambda expressions for building validation rules for your business objects.
2. Agenda
• Fluent Validation – Who am I?
• Validator Creation
• Built in Validators
• Validator customizations
• Localization support
• Benefits
• Conclusion
3. Fluent Validation – Who am I?
• Open source Validation library for .net
• Uses Fluent interfaces and lambda expressions
for building validation rules
• Source available in GitHub
• Available as Nu-get packages
– FluentValidation
– FluentValidation.MVC3
– FluentValidation.MVC4
• Signed binaries are also available
4. Validator Creation
• Validator class : AbstractValidator<>
• Validation Result
– IsValid
– Errors
• Chaining Validators
• Throwing Exceptions
• Validators for Complex properties
• Validators for Collections
• Rule Sets
5. Built in Validators
• NotNull Validator
• NotEmpty Validator
• NotEqual Validator
• Equal Validator
• Length Validator
• Less Than Validator
6. Built in Validators (contd.,)
• Less Than Or Equal Validator
• Greater Than Validator
• GreaterThan Or Equal Validator
• Predicate Validator (aka Must)
• RegEx Validator
• Email Validator
7. Validator customizations
• Overriding the default error message
– .WithMessage(“…”)
• Overriding the Default Property Name
– .WithName(“Family name")
• Specifying a condition (When/Unless)
– .When(Student.Age > 30)
• Cascading
– .Cascade(CascadeMode.StopOnFirstFailure)
8. Localization support
• It supports the following languages:
– English
– French
– German
– Dutch
– Spanish
– Portuguese
10. Localization support (contd.,)
• Resource names that can be customized
email_error equal_error
exact_length_error exclusivebetween_error
greaterthan_error greaterthanorequal_error
inclusivebetween_error length_error
lessthan_error lessthanorequal_error
notempty_error notequal_error
notnull_error predicate_error
regex_error
11. Benefits
• It separates validation from the Model
• Unit testing is easier
• Can perform different conditional validations
on different properties
• Re-usability
• No need for annotations (which make the
code looks clumsy)
RuleFor(customer => customer.Surname).NotNull().WithMessage("Please ensure that you have entered your Surname");RuleFor(customer => customer.Surname).NotNull().WithName("Last name");RuleFor(customer => customer.CustomerDiscount).GreaterThan(0).When(customer => customer.IsPreferredCustomer);RuleFor(x => x.Surname).Cascade(CascadeMode.StopOnFirstFailure).NotNull().NotEqual("foo");