[英]How to create a custom Compare attribute with client-side validation?
標題說明了一切,但我會在這里添加一些背景知識。
直到最近,我一直在使用MVC已經編寫的CompareAttribute
來比較兩個值,在這種情況下是密碼及其確認。 它運行良好,除了此屬性不顯示由正在比較的屬性的[Display(Name = "Name")]
屬性設置的[Display(Name = "Name")]
。
以下是要比較的兩個屬性:
[Required]
[Display(Name = "New Password")]
public string New { get; set; }
[Compare("New")]
[Display(Name = "Confirm Password")]
public string ConfirmPassword { get; set; }
驗證消息如下:
'Confirm Password' and 'New' do not match.
這有效,但顯然不如它應該的那么好。 New
應顯示為“ New Password
,由“ Display
屬性指定。
我已經完成了這項工作,但並非完全如此。 以下實現(由於某種原因)修復了未獲取屬性的指定名稱的問題,但我不確定原因:
public class CompareWithDisplayNameAttribute : CompareAttribute
{
public CompareWithDisplayNameAttribute(string otherProperty)
: base(otherProperty)
{
}
}
現在,即使這有效,客戶端驗證也不起作用。 我在另一個問題中得到了答案,建議使用這樣的東西
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareWithDisplayName), typeof(CompareAttributeAdapter))
在我的Global.asax
,但CompareAttributeAdapter
實際上並不存在。
所以我在這里。 我的自定義CompareWithDisplayName
屬性正確使用了Display
屬性,但客戶端驗證完全丟失。
如何以最干凈的方式使用此解決方案進行客戶端驗證?
如果您希望自定義比較屬性與客戶端驗證一起使用,則需要實現IClientValidatable
。 這有GetValidationRules
,您可以在其中進行任何您可能希望的自定義驗證。
例
public class CompareWithDisplayNameAttribute : CompareAttribute, IClientValidatable
{
public CompareWithDisplayNameAttribute(string otherProperty)
: base(otherProperty)
{
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata, ControllerContext context)
{
// Custom validation goes here.
yield return new ModelClientValidationRule();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.