Using FluentValidation for simple function arguments validation

Oct 3, 2013 at 11:39 PM
Instead of introduction some utility methods, I would like to use the fluetnvalidation for my simple cases and just throw if say an argument is null. I started trying something like this below. This issue is that the RuleFor method wants an expression the typically is part of a POCO. I don't have the case consequently, I can't put my argument name in the validation output. Any idea? Thanks.
    public static class Requires
        public static void NotNull<T>(T arg, string name, string message)
            var validator = new InlineValidator<T>() 
                v => v.RuleFor(x => x).NotNull().WithName(name).WithMessage(message)


    class Program

        static void Main(string[] args)
            object thismightbeanarg = null;

            Requires.NotNull(args, "args", "cannot be null");
            Requires.NotNull(thismightbeanarg, "this arg", "cannot be null");

Oct 4, 2013 at 8:36 AM

As you're explicitly calling WithMessage, then the name will not show up in the output. WithMessge always overrides the name, unless it contains the {PropertyName} placeholder.

That being said, I would highly recommend that you don't use FluentValidation for this. FluentValidation is designed for validating properties on objects, not stand-alone values. By doing this you are:
  • making your validation needlessly complex
  • introducing a massive performance impact for no benefit
If you're not validating properties on objects then I would recommend investigate a simpler solution.