エディター テンプレートを使用するページでクライアント側の検証を機能させようとしています。
私のビューモデルの簡単な例は次のとおりです。
[Validator(typeof(ValidationTestModelValidator))]
public class ValidationTestModel
{
public string Name { get; set; }
public string Age { get; set; }
public ChildModel Child { get; set; }
}
子モデルは次のとおりです。
public class ChildModel
{
public string ChildName { get; set; }
public string ChildAge { get; set; }
}
私のバリデーターは次のとおりです。
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());
}
}
子モデルのバリデーターは次のとおりです。
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");
}
}
Application_Start() に以下を追加して、FluentValidation.Net を MVC3 に登録しました。
// Register FluentValidation.Net
FluentValidationModelValidatorProvider.Configure();
これにより、Name と Age の 2 つのプロパティに対して控えめなクライアント側の検証が完全に生成されますが、ChildModel のプロパティに対しては何も生成されません。
ここで私が間違っていることはありますか?
更新: ChildModel に Validator 属性で注釈を付ければ問題ないようですが、条件付きで検証を適用したいので、SetValidator() を使用します。