我有一個ValidationAttribute,我已經創建了Server和Client之間共享的。爲了在數據幫助器類中引用時將驗證屬性正確生成到客戶端,我必須非常詳細地說明如何構建它。驗證錯誤的自定義ValidationAttribute未正確顯示
我遇到的問題是,當我從我的自定義驗證返回的ValidationResult某種原因屬性類爲其他驗證客戶端UI屬性它不處理相同。它不會顯示錯誤,它不會執行任何操作。它會正確驗證對象,但它不會顯示失敗的驗證結果。
下面是我的一個自定義驗證類的代碼。
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。如果我對視圖模型中的值使用驗證結果,那麼它將正確驗證。我需要找到一種方法,可以從生成的代碼中正確驗證。
任何想法將非常感激。
非常感謝。這解決了我的問題。 –