I'm trying to get client side validation working for a page that uses editor templates.
A simplified example of my view model is e.g.:
[Validator(typeof(ValidationTestModelValidator))]
public class ValidationTestModel
{
public string Name { get; set; }
public string Age { get; set; }
public ChildModel Child { get; set; }
}
The child model is e.g.:
public class ChildModel
{
public string ChildName { get; set; }
public string ChildAge { get; set; }
}
My validator is e.g.:
public class ValidationTestModelValidator : AbstractValidator<ValidationTestModel>
{
public ValidationTestModelValidator()
{
RuleFor(m => m.Name)
.NotEmpty()
.WithMessage("Please enter the name");
RuleFor(m => m.Age)
.NotEmpty()
.WithMessage("Please enter the age");
RuleFor(m => m.Age)
.Matches(@"\d*")
.WithMessage("Must be a number");
RuleFor(m => m.Child)
.SetValidator(new ChildModelValidator());
}
}
And the child model validator is e.g.:
public class ChildModelValidator : AbstractValidator<ChildModel>
{
public ChildModelValidator()
{
RuleFor(m => m.ChildName)
.NotEmpty()
.WithMessage("Please enter the name");
RuleFor(m => m.ChildAge)
.NotEmpty()
.WithMessage("Please enter the age");
RuleFor(m => m.ChildAge)
.Matches(@"\d*")
.WithMessage("Must be a number");
}
}
I have registered FluentValidation.Net with MVC3 by adding the following to Application_Start():
// Register FluentValidation.Net
FluentValidationModelValidatorProvider.Configure();
This generates unobtrusive client side validation perfectly for the two properties Name and Age, but nothing for the properties on the ChildModel.
Any ideas what I'm doing wrong here?
Update: It seems to work ok if I just annotate the ChildModel with the Validator attribute, however I want to apply the validation conditionally, hence the use of SetValidator().
RuleFor
is this from mvc libraries or external library? if external which one are u using? – DarthVader