@ChildContent
public class MyModel : IValidatableObject
{
public string Name { get; set; }
public IEnumerable Validate(ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(Name))
{
yield return new ValidationResult("Name is required.", new[] { nameof(Name) });
}
}
}
public class ParentModel : IValidatableObject
{
public MyModel MyModel { get; set; }
public IEnumerable Validate(ValidationContext validationContext)
{
if (MyModel == null)
{
yield return new ValidationResult("MyModel is required.", new[] { nameof(MyModel) });
}
else
{
foreach (var result in Validator.ValidateObject(MyModel, new ValidationContext(MyModel))) // 需要引用System.ComponentModel.DataAnnotations命名空间
{
yield return result;
}
}
}
}
通过以上步骤,即可在自定义组件中使用Validation组件实现表单验证。