簡單的自定義的驗證,MVC3簡單的自定義驗證
我的模式和自定義的驗證:
public class Registration
{
[Required(ErrorMessage = "Date of Birth is required")]
[AgeV(18,ErrorMessage="You are not old enough to register")]
public DateTime DateOfBirth { set; get; }
}
public class AgeVAttribute : ValidationAttribute
{
private int _maxAge;
public AgeVAttribute(int maxAge)
{
_maxAge = maxAge;
}
public override bool IsValid(object value)
{
return false; <--- **this never gets executed.... what am I missing?**
}
}
(請參見上面的在線評論)
觀點:
@using (Html.BeginForm()) {
@Html.ValidationSummary("Errors")
<fieldset>
<legend>Registration</legend>
<div class="editor-label">
@Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateOfBirth)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
接收模型的控制器是什麼樣的? – 2012-04-13 16:09:19
我已經在一個空白的MVC項目中嘗試了您的代碼,並且發生了IsValid調用,因爲它應該發生。 – Iridio 2012-04-13 16:10:30
您是否會在使用「註冊」類型的模型時提供「操作」方法?我測試了你的代碼,它在服務器端工作。由於您的'AgeVAttribute'沒有實現IClientValidatable,所以客戶端驗證關閉。 – Kibria 2012-04-13 16:33:04