1

検証に DataAnnotations を使用しています (クライアント側を含む)

複数のフィールドを持つフォームがあります。個々のフィールドの基本的な検証は正常に機能します。現在、少なくとも 1 つのフィールドに値が必要なフィールドがいくつかあります (3 つのフィールドがある場合は、1 番目または 2 番目または 3 番目のフィールドのいずれかに値が必要です)。

このサイトのかなりの数の投稿といくつかのブログ エントリを読みました。しかし、上記のシナリオで機能する解決策が見つかりませんでした。何かを見逃したか、間違ったやり方をしている可能性があります。

これを手伝ってもらえますか?

4

1 に答える 1

2

これを試して

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class EitherOr : ValidationAttribute
{
    private const string _defaultErrorMessage = "'{0}' OR '{1}' OR '{2}' must have a value";
    private readonly object _typeId = new object();

    public EitherOr(string prop1, string prop2, string prop3)
        : base(_defaultErrorMessage)
    {
        Prop1 = prop1;
        Prop2 = prop2;
        Prop3 = prop3;

    }

    public string Prop1 { get; private set; }
    public string Prop2 { get; private set; }
    public string Prop3 { get; private set; }

    public override object TypeId
    {
        get
        {
            return _typeId;
        }
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, Prop1, Prop2,Prop3);
    }

    public override bool IsValid(object value)
    {
        if(string.IsNullOrEmpty(Prop1)&&string.IsNullOrEmpty(Prop2) && string.IsNullOrEmpty(Prop3))
        {
            return false;
        }
        return true;
    }

次に、クラスを eitherOr 属性でマークします。

[EitherOr("Bar","Stool","Hood", ErrorMessage = "please supply one of the properties")]
    public class Foo
    {
        public string Bar{ get; set;}
        public string Stool{ get; set;}
        public string Hood{ get; set;}
    }

文字列プロパティを使用したことに注意してください。プロパティが他のタイプの場合は、必ずIsValid(object value)検証を変更してください

于 2010-09-22T15:35:13.993 に答える