Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a single property with the Fluent Validation Library for .Net

Can you validate just a single property with the Fluent Validation Library, and if so how? I thought this discussion thread from January of 2009 showed me how to do it via the following syntax:

validator.Validate(new Person(), x => x.Surname);

Unfortunately it doesn't appear this works in the current version of the library. One other thing that led me to believe that validating a single property might be possible is the following quote from Jeremy Skinners' blog post:

"Finally, I added the ability to be able to execute some of FluentValidation’s Property Validators without needing to validate the entire object. This means it is now possible to stop the default “A value was required” message from being added to ModelState. "

However I do not know if that necessarily means it supports just validating a single property or the fact that you can tell the validation library to stop validating after the first validation error.

like image 845
Blegger Avatar asked May 17 '10 15:05

Blegger


People also ask

How do you validate fluently?

To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate. Customer customer = new Customer(); CustomerValidator validator = new CustomerValidator(); ValidationResult result = validator. Validate(customer);

What is fluent validation in .NET core?

Fluent Validation is a free to use . NET validation library that helps you make your validations clean, easy to create, and maintain. It even works on external models that you don't have access to, with ease. With this library, you can separate the model classes from the validation logic like it is supposed to be.

What is fluent validation C#?

FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic.


2 Answers

According to this discussion on CodePlex, that ability is added by way of extension methods. You would need to import the FluentValidation namespace to have those show up in IntelliSense.

like image 137
patridge Avatar answered Oct 16 '22 14:10

patridge


For anyone else stumbling upon this problem. In FluentValidation v9.3.0 you would do:

_Validator.Validate(ClassInstance, 
                opt=> opt.IncludeProperties(x => x.SomePropertyOfTheClassInstance));
like image 4
sebastian.roibu Avatar answered Oct 16 '22 16:10

sebastian.roibu