ので、 iはフィールドをたくさん持っている「ユーザー」モデルを持っていますが、次はIMPTものです:mvcモデルとviewmodel?
public int Id {get;set;}
public string Username { get; set; }
public string Pwd { get; set; }
と私は私が上で使用するパスワードを検証ビューモデルを持っています別のコントローラ:
public class ConfirmPassword : IValidatableObject
{
[Required]
public string Password { get; set; }
[Required(ErrorMessage="Confirm Password field is required.")]
public string ConfirmPwd { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
string regex1 = @"^.{8,10}$"; // 8 - 10 characters
Match requirement1 = Regex.Match(Password, regex1);
if (Password != ConfirmPwd)
yield return new ValidationResult("Password and Confirm Password is not identical.");
if (!requirement1.Success)
yield return new ValidationResult("Password must be between 8 and 10 characters.");
}
}
ビューモデルをモデルエンティティに接続する方法はありますか?またはちょうど私の唯一のオプションコードを貼り付けコピー?私はコードがIValidateObjectを持っている必要があるので、コピー貼り付けはできません。バックグラウンド監査がたくさんあるので、Userエンティティ全体を壊してしまいます。プロファイルが編集/作成されるたびにパスワードを検証する必要があります。
編集: みなさんは混乱してしまいます。基本的には、私は確認パスワードに必要な複数の検証を持っています。これはデータアノテーションでは処理できません。確かにconfirmpassword viewmodelです。この検証はUserモデルに適用したいが、 "ConfirmPassword"フィールドを追加する必要はありません。データベース上に別のフィールドは必要ありません。私の質問は、ビューのPOSTとパスワードフィールドがその要件を満たさないときはいつも、私がconfirmapasswordから持っているバリデーションを強制するのですか?
namespace
{
public class User
{
public int Id {get;set;}
public string Username { get; set; }
public string Pwd { get; set; }
}
}
namespace
{
public class ConfirmPassword : IValidatableObject
{
[Required]
public string Password { get; set; }
[Required(ErrorMessage="Confirm Password field is required.")]
public string ConfirmPwd { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
string regex1 = @"^.{8,10}$"; // 8 - 10 characters
string regex2 = @"(?:.*?[A-Z]){1}"; // 1 uppercase
string regex3 = ""; // 1 lowercase
string regex4 = ""; // 1 numeric
Match requirement1 = Regex.Match(Password, regex1);
Match requirement2 = Regex.Match(Password, regex2);
Match requirement3 = Regex.Match(Password, regex3);
Match requirement4 = Regex.Match(Password, regex4);
if (Password != ConfirmPwd)
yield return new ValidationResult("Password and Confirm Password is not identical.");
if (!requirement1.Success)
yield return new ValidationResult("Password must be between 8 and 10 characters.");
if (!requirement2.Success)
yield return new ValidationResult("Password must contain at least 1 uppercase letter.");
if (!requirement3.Success)
yield return new ValidationResult("Password must contain at least 1 lowercase letter.");
if (!requirement4.Success)
yield return new ValidationResult("Password must contain at least 1 numeric character.");
}
}
}
なぜ私は「StringLengthAttribute」 –
を使用していません。これは私の唯一の妥当性検査ではありません。私はちょうどそれを切った。正規表現を使用する4つ以上のものがあります。 – gdubs
状況を制御できる場合は、パスワードの上限の長さを使用しないでください。パスワードが8〜10文字であることを外界に伝えることは、ブルートフォース攻撃の際に使用する文字数をハッカーに伝えます。 –