Validating a view model after custom model binding

Adapted from here:
https://stackoverflow.com/questions/13684354/validating-a-view-model-after-custom-model-binding

Usage:

CustomModelBinderHelper.DoValidation(bindingContext, indexViewModel);

Implementation:

    public static class CustomModelBinderHelper
    {
        /// <summary>
        /// https://stackoverflow.com/a/22652195/249895
        /// </summary>
        /// <param name="bindingContext"></param>
        /// <param name="model"></param>
        public static void DoValidation(ModelBindingContext bindingContext, IValidatableObject model)
        {
            var validationResults = new HashSet<ValidationResult>();
            var isValid = Validator.TryValidateObject(model, new ValidationContext(model, null, null), validationResults, true);
            if (!isValid)
            {
                var resultsGroupedByMembers = validationResults
                    .SelectMany(_ => _.MemberNames.Select(
                         x => new
                         {
                             MemberName = x ?? "",
                             Error = _.ErrorMessage
                         }))
                    .GroupBy(_ => _.MemberName);

                foreach (var member in resultsGroupedByMembers)
                {
                    bindingContext.ModelState.AddModelError(
                        member.Key,
                        string.Join(". ", member.Select(_ => _.Error)));
                }
            }
        }
    }

 

To be noted that objects have to implment System.ComponentModel.DataAnnotations.IValidatableObject interface.

Leave a Reply

Your email address will not be published. Required fields are marked *