2014-10-17 106 views
0

請幫助,任何人都可以告訴我爲什麼我的自定義驗證沒有在我的mvc 4項目中開火。MVC 4驗證

這裏是我的模型......

[Required(ErrorMessage = "Old Password is required field.")] 
[VerifyOldPassword(ErrorMessage = "Invalid Old Password.")] 
public string PasswordOld { get; set; } 

屬性類

public class VerifyOldPasswordAttribute : ValidationAttribute 
{ 
    public VerifyOldPasswordAttribute() 
    { 

    } 
    public override bool IsValid(object value) 
    { 

     string currentValue = value as string; 
     string referrenceValue = mtdGetOldPassword(); 

     if (currentValue != referrenceValue) 
     { 
      return false; 
     } 

     return true; 
    } 
} 

瀏覽:

@Html.PasswordFor(m => m.PasswordOld, new { @class = "txtInputLong" }) 
@Html.ValidationMessageFor(m => m.PasswordOld, "", 
      new { style = "font-family:Arial;font-size:small;font-weight:bold;color:red" }) 

預先感謝您....

+1

剛剛複製你的代碼到我的項目,它工作正常(或者是你希望客戶端驗證呢?) – 2014-10-17 05:40:01

+1

您創建的自定義驗證只是僅適用於服務器端,但不是因爲它的客戶端沒有實現IClientValidatable。當沒有提供有效數據時,檢查您的ModelState.IsValid屬性是否爲false。 – Venkat 2014-10-17 06:22:27

+0

@Venkat,我懷疑從OP的代碼,客戶端驗證不會在這裏工作,因爲它從某個地方(數據庫)獲取舊值?因此無論是內置[RemoteAttribute](http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute(v = vs.118).aspx)或[CompareAttribute](http: //msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.compareattribute%28v=vs.110%29.aspx)可能是一個更好的解決方案,客戶端驗證 – 2014-10-17 06:47:11

回答

0

請檢查這些設置正確或n ot在你的項目的web.config?

<configuration> 
    <appSettings> 
    <add key="ClientValidationEnabled" value="true" /> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 
    </appSettings> 
</configuration> 
+0

是的,它與上面提供的設置相同... – marai 2014-10-17 05:38:17

+0

您是否收到任何錯誤? JavaScript或jQuery的錯誤? – Mukund 2014-10-17 05:42:07