だから私は、ユーザーとビジネス パートナーを登録している web アプリを持っています。
これは私のモデルがどのように見えるかです
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" });
}
}
問題は次のとおりです。フォームを送信すると、Validate in CompanyModel が呼び出され、Validate in RegistrationModel も呼び出されます。しかし、Validate in UserModel も呼び出されるようにしたい...
更新:最初の問題を解決しました:これらはアップグレード後のモデルです:)
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 が 2 回実行される理由がわかりません??. なにか提案を?