Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: How to convert this code to use Fluent Validation

$
0
0
Hello,
I am currently moving away from DataAnnotations to Fluent Validation. I had no problem to 
do the migration of code except here for my unit testing helper.
I have created this helpers to validate my models with DataAnnotations and would like to
rewrite it to use Fluent Validation.
How would you do it?
        public static void ValidateModel(this Controller controller, object model)
        {
            controller.ModelState.Clear();

            var validationResults = ValidateModel(model);

            foreach (var result in validationResults)
            {
                if (result.MemberNames.Count() == 0)
                {
                    controller.ModelState.AddModelError("", result.ErrorMessage);
                }
                else
                {
                    foreach (var name in result.MemberNames)
                    {
                        controller.ModelState.AddModelError(name, result.ErrorMessage);
                    }
                }
            }
        }

        public static List<ValidationResult> ValidateModel(object model)
        {           
            ValidationContext validationContext = new ValidationContext(model, null, null);
            List<ValidationResult> validationResults = new List<ValidationResult>();

            Validator.TryValidateObject(model, validationContext, validationResults, true);

            return validationResults;
        }
Thanks in advance!

Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>