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

New Post: Collection validation is not letting WithMessage to show the custom message

$
0
0
Hi,
I have a parent and associated child model like following :

      Parent Model:

[FluentValidation.Attributes.Validator(typeof(ParentValidator))]
    public class ParentModel
    {
        [DisplayName("Parent Name")]
        public string Name { get; set; }
 
        public List<ChildModel> Children { get; set; }
 
    }
 ChildModel:
 
    public class ChildModel
    {
        public string Name { get; set; }
        public double? Age { get; set; }
    }
 
I have the validators like :
 
ParentValidator:
    public class ParentValidator : AbstractValidator<ParentModel>
    {
        public ClassValidator()
        {
            RuleFor(m => m.Name).NotNull().WithMessage("Parent Name is required. Please enter something.");
            RuleFor(cls => cls.Children).SetCollectionValidator(new ChildValidator()).WithMessage("For Children, the Name and Age are mandatory.");
        }
    }
ChildValidator:

              public class ChildValidator:AbstractValidator<ChildModel>
              {
                       public ChildValidator()
                       {
                              RuleFor(fee => fee.Name).NotNull();
                              RuleFor(fee => fee.Age).NotNull();
                        }
              }
Here my problem is when the Children inside Parent model is not having Name And/Or Amount then i am expecting the error message to be : For Children, the Name and Age are mandatory. Instead it is displaying the default validation messages multiple times(if there are more than one children) like: 'Name' must not be empty. 'Age' must not be empty.

So, what i need to do, to get the expected message (preferably one custom message for all children)

Thanks in advance,

 



Viewing all articles
Browse latest Browse all 1917


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