question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

FluentValidation throws NullReferenceException when validation object is null

See original GitHub issue

FluentValidation throws NullReferenceException when the object is null

Expected: ValidationResult with Message “Entity cannot be null”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentValidation;

namespace ConsoleApplication11
{
    public class Entity
    {
        public string Type { get; set; }
    }

    public class EntityValidator : AbstractValidator<Entity>
    {
        public EntityValidator()
        {
            this.RuleFor(a => a)
             .NotEmpty()
             .WithMessage("Entity cannot be null");


            this.RuleFor(a => a.Type)
                .NotEmpty()
                .WithMessage("Type cannot be null or empty");

        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Entity entity = null;


            var validator = new EntityValidator();


            validator.Validate(entity);
        }
    }

}

Stacktrace:

   at lambda_method(Closure , Entity )
   at FluentValidation.Internal.Extensions.<>c__DisplayClass1`2.<CoerceToNonGeneric>b__0(Object x) in c:\Projects\FluentValidation\src\FluentValidation\Internal\Extensions.cs:line 108
   at FluentValidation.Validators.PropertyValidatorContext.get_PropertyValue() in c:\Projects\FluentValidation\src\FluentValidation\Validators\PropertyValidatorContext.cs:line 53
   at FluentValidation.Validators.PropertyValidator.Validate(PropertyValidatorContext context) in c:\Projects\FluentValidation\src\FluentValidation\Validators\PropertyValidator.cs:line 69
   at FluentValidation.Internal.PropertyRule.InvokePropertyValidator(ValidationContext context, IPropertyValidator validator, String propertyName) in c:\Projects\FluentValidation\src\FluentValidation\Internal\PropertyRule.cs:line 360
   at FluentValidation.Internal.PropertyRule.<Validate>d__10.MoveNext() in c:\Projects\FluentValidation\src\FluentValidation\Internal\PropertyRule.cs:line 241
   at System.Linq.Enumerable.<SelectManyIterator>d__1`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at FluentValidation.AbstractValidator`1.Validate(ValidationContext`1 context) in c:\Projects\FluentValidation\src\FluentValidation\AbstractValidator.cs:line 113
   at FluentValidation.AbstractValidator`1.Validate(T instance) in c:\Projects\FluentValidation\src\FluentValidation\AbstractValidator.cs:line 94
   at ConsoleApplication11.Program.Main(String[] args) in c:\users\administrator\documents\visual studio 2015\Projects\ConsoleApplication11\Program.cs:line 37
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:11 (3 by maintainers)

github_iconTop GitHub Comments

9reactions
ryanbueningcommented, Aug 21, 2017

Not being able to validate against null objects prevents me from using FV. I have nested classes in my ViewModel that can be null.

7reactions
theofaniscommented, Apr 6, 2016

@spawluk That’s the exact problem in my case. The bound model from the JSON payload, let’s say in a POST request, is null, so the validator never kicks in, so it needs a custom way to handle this case. Not pretty.

Read more comments on GitHub >

github_iconTop Results From Across the Web

FluentValidation NullReferenceException - Way to prevent ...
@Ryan Buening you are trying to call instance method of null object so you are getting NullReferenceException and this is normal for c#....
Read more >
Other Advanced Features — FluentValidation documentation
If you use the ValidateAndThrow method to throw an exception when validation fails FluentValidation will internally throw a ValidationException . You can ...
Read more >
FluentValidation throws NullReferenceException when ...
FluentValidation throws NullReferenceException when the object is null. Expected: ValidationResult with Message "Entity cannot be null"
Read more >
c# - Fluent Validation of Objects
Using Require , it's clearer that the lambda defines what must be the case, and the message applies to when the requirement is...
Read more >
C# – 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...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found