I am trying to validate List of input Object in my webApi 2.
but it's not validating. Modelstate always is set to true.
Sample code:
public class A
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ClassAValidator : AbstractValidator<A>
{
public classAValidator()
{
RuleSet("ClassA",()=>{
RuleFor(x => x.Id).NotEmpty().WithMessage("The Idcan't be Empty or Zero");
RuleFor(x => x.Name).NotEmpty().Length(10).WithMessage("Name Should be Six Char length");
});
}
}
Note: The string field we need to be exact 6 characters.
Api:
[HttpPut]
public async Task<IHttpActionResult> Put([FromBody] List<A> alist)
{
if(!ModelState.IsValid) throw new InvalidDataException(ModelState,"Data Validation Failed for Upload Class A");
// Model State is Always true
}
Can anyone point what I have missed?
Update: I tried as shown in Should i create a new Type for Collection in FluentValidation?
but still having the same issue.
Solved Update:
Issue is usage of Ruleset caused the validation Not getting Triggered. On removing "RuleSet" it worked even without having definition of List[A] Validator class.
Message from Jeremy Skinner : First problem is your rules are wrapped in a Ruleset, so they'll never be executed. Rulesets are opt-in, and the automatic integration only invokes rules not in a ruleset.