Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation rule for null object

I've been trying to work out how to create a FluentValidation rule that checks if the instance of an object it's validating is not null, prior to validating it's properties.

I'd rather encapsulate this null validation in the Validator rather then doing it in the calling code.

See example code below with comments where the required logic is needed:

namespace MyNamespace {     using FluentValidation;      public class Customer     {         public string Surname { get; set; }     }      public class CustomerValidator: AbstractValidator<Customer>      {         public CustomerValidator()          {             // Rule to check the customer instance is not null.              // Don't continue validating.              RuleFor(c => c.Surname).NotEmpty();         }     }      public class MyClass     {         public void DoCustomerWork(int id)         {             var customer = GetCustomer(id);             var validator = new CustomerValidator();              var results = validator.Validate(customer);              var validationSucceeded = results.IsValid;         }          public Customer GetCustomer(int id)         {             return null;         }     } } 

So my question is how do I check in the CustomerValidator() constructor that the current instance of customer is not null and abort further rule processing if it is null?

Thanks in advance.

like image 636
Bern Avatar asked Jun 13 '13 19:06

Bern


Video Answer


1 Answers

You should be able to override the Validate method in your CustomerValidator class.

public class CustomerValidator: AbstractValidator<Customer>  {     // constructor...      public override ValidationResult Validate(Customer instance)     {         return instance == null              ? new ValidationResult(new [] { new ValidationFailure("Customer", "Customer cannot be null") })              : base.Validate(instance);     } } 
like image 73
Matthew Avatar answered Sep 18 '22 19:09

Matthew