.NETフレームワークは、単独であなたの検証ロジックを行使することができますValidatorクラスが付属しています。テストするコードは次のようになります。
var achievement = new AchievementVM();
var context = new ValidationContext(achievement,
serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(achievement, context, results, true);
Assert.IsTrue(results.Any(vr => vr.ErrorMessage == "The title field is required."));
achievement.Title = "Really really long title that violates "
+ "the range constraint and should not be accepted as "
+ "valid input if this has been done correctly.";
Validator.TryValidateObject(achievement, context, results, true);
Assert.IsTrue(results.Any(vr => vr.ErrorMessage == "Title must be 100 characters or less."));
属性の存在を検索するカスタムユーティリティは必要ありません。 Validatorクラスは、あなたのために作業を行い、MVCインフラストラクチャと同じようにValidationResultコレクションに値を設定します。この方法で
良い過去記事はK. Scott Allen's blogで見つけることができます。
このデータの注釈は何ですか?それは妥当性検査なのでしょうか? –
これは、検証されるべきコンポーネントのマークです。データアノテーションを使用した手動検証の実例:http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx –