はい、 Validator.TryValidateObject(SomeObject,...)を呼び出す必要があります 。
例は
http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations です。 aspx
...ジューシービットは....
var vc = new ValidationContext(theObject, null, null);
var vResults = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(theObject, vc, vResults, true);
// isValid has bool result, the actual results are in vResults....
もっと詳しく説明させてください。バリデーターが検証ルーチンを呼び出す前に、すべての注釈を有効にする必要があります。ここで、問題の可能性が最も高いものを説明するテストプログラムを追加しました
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ValidationDemo
{
class Program
{
static void Main(string[] args)
{
var ord = new Order();
// If this isnt present, the validate doesnt get called since the Annotation are INVALID so why check further...
ord.Code = "SomeValue"; // If this isnt present, the validate doesnt get called since the Annotation are INVALID so why check further...
var vc = new ValidationContext(ord, null, null);
var vResults = new List<ValidationResult>(); // teh results are here
var isValid = Validator.TryValidateObject(ord, vc, vResults, true); // the true false result
System.Console.WriteLine(isValid.ToString());
System.Console.ReadKey();
}
}
public class Order : IValidatableObject
{
public int Id { get; set; }
[Required]
public string Code { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var vResult = new List<ValidationResult>();
if (Code != "FooBar") // the test conditions here
{
{
var memberList = new List<string> { "Code" }; // The
var err = new ValidationResult("Invalid Code", memberList);
vResult.Add(err);
}
}
return vResult;
}
}
}