所以我有一个正在注册用户和业务合作伙伴的网络应用程序。
这就是我的模型的样子
public class UserModel : IValidatableObject
{
//here are some properties and methods that I am using in Validate method
public CompanyModel Company { get; set; } //this is user Company
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.UserWithEmailExists())
yield return new ValidationResult("Email already exists", new[] { "Email" });
if (this.UserWithUsernameExists())
yield return new ValidationResult("Username already exists", new[] { "Username" });
}
}
public class CompanyModel : IValidatableObject
{
//again here are some properties that i am using in Validate
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.Phone == null && this.Mobile == null)
yield return new ValidationResult("The Phone field is required", new[] { "Phone" });
}
}
//this is the model passed to the view
public sealed class RegistrationModel : UserModel, IValidatableObject
{
public new IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.Password != this.PasswordValidation)
yield return new ValidationResult("Ponovite prejšnji vnos", new[] { "PasswordValidation" });
}
}
问题是:当我提交表单时,CompanyModel 中的 Validate 被调用,并且 RegistrationModel 中的 Validate 也被调用。但我也想在 UserModel 中调用 Validate...
更新:我解决了第一个问题:这些是升级后的模型:)
public class UserModel : IValidatableObject
{
//here are some properties and methods that I am using in Validate method
public CompanyModel Company { get; set; } //this is user Company
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.UserWithEmailExists())
yield return new ValidationResult("Email already exists", new[] { "Email" });
if (this.UserWithUsernameExists())
yield return new ValidationResult("Username already exists", new[] { "Username" });
}
}
public class CompanyModel : IValidatableObject
{
//again here are some properties that i am using in Validate
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.Phone == null && this.Mobile == null)
yield return new ValidationResult("The Phone field is required", new[] { "Phone" });
}
}
//this is the model passed to the view
public sealed class RegistrationModel : UserModel, IValidatableObject
{
public override new IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
//this is needed so that UserModel validation executes
foreach (var result in base.Validate(validationContext))
{
yield return result;
}
if (this.Password != this.PasswordValidation)
yield return new ValidationResult("Ponovite prejšnji vnos", new[] { "PasswordValidation" });
}
}
现在验证工作正常。我只是不知道为什么 CompanyModel 中的 Validate 执行两次???。有什么建议吗?