サーバーとクライアントの間で共有される ValidationAttribute を作成しました。データ ヘルパー クラス内で参照されたときにクライアントに適切に生成される検証属性を取得するには、その構築方法を非常に具体的にする必要がありました。
私が抱えている問題は、何らかの理由で、カスタム検証属性クラスから ValidationResult を返すときに、クライアント UI の他の検証属性と同じように処理されないことです。エラーを表示する代わりに、何もしません。ただし、オブジェクトは適切に検証されますが、失敗した検証結果は表示されません。
以下は、私のカスタム検証クラスの 1 つのコードです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace Project.Web.DataLayer.ValidationAttributes
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class DisallowedChars : ValidationAttribute
{
public string DisallowedCharacters
{
get
{
return new string(this.disallowedCharacters);
}
set
{
this.disallowedCharacters = (!this.CaseSensitive ? value.ToLower().ToCharArray() : value.ToCharArray());
}
}
private char[] disallowedCharacters = null;
private bool caseSensitive;
public bool CaseSensitive
{
get
{
return this.caseSensitive;
}
set
{
this.caseSensitive = value;
}
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null && this.disallowedCharacters.Count() > 0)
{
string Value = value.ToString();
foreach(char val in this.disallowedCharacters)
{
if ((!this.CaseSensitive && Value.ToLower().Contains(val)) || Value.Contains(val))
{
return new ValidationResult(string.Format(this.ErrorMessage != null ? this.ErrorMessage : "'{0}' is not allowed an allowed character.", val.ToString()));
}
}
}
return ValidationResult.Success;
}
}
}
これは、サーバーとクライアントの両方でプロパティの上で使用する方法です。
[DisallowedChars(DisallowedCharacters = "=")]
そして、バインディングをセットアップするいくつかの異なる方法を試しました。
{Binding Value, NotifyOnValidationError=True}
としても
{Binding Value, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, ValidatesOnNotifyDataErrors=True}
これらのいずれも、バインドされているフォームがエントリを検証するようには見えません。TextBoxes、XamGrids にバインドされた値でこの属性を使用しようとしましたが、どちらも適切に検証されませんでした。
この問題は、サーバー側で ValidationResult を使用しようとしているときにのみ発生するようです。ビューモデルの値で検証結果を使用すると、適切に検証されます。ただし、生成されたコードからこれを適切に検証する方法を見つける必要があります。
どんな考えでも大歓迎です。