使用 ExtJS 實現 ASP.NET MVC 2 客戶端驗證
在 ASP.NET MVC 2 中, 客戶端表單驗證信息不再是直接調用微軟自己提供的方法, 而是將客戶端表單驗證的元數據放到了一個變量 (window.mvcClientValidationMetadata) 之中, 為實現第三方的客戶端驗證提供了可能, 由于工作中大量的使用到了 ExtJS ,于是抽時間用 ExtJS 實現了 ASP.NET MVC 2 客戶端驗證機制,主要有如下特點:
- 只依賴 Ext core 即可使用,不需要完整版本的 ExtJS, 當然,如果有完整版 ExtJS 的話, 還可以調用 Ext.form.VTypes 的表單驗證方法;
- 使用方法完全遵循 ASP.NET MVC 2 提供的客戶端驗證機制,實現了默認的 required 、regularExpression 、 number 、range 、stringLength 客戶端驗證函數;
- 可以根據 ASP.NET MVC 2 提供的驗證擴展機制進行相應的擴展。
使用方法如下:
1、在要進行驗證的 Model 上添加驗證標記, 代碼如下:
public class RegisterModel {
[Required(ErrorMessage = "用戶名必須填寫!")]
[DisplayName("用戶名:")]
public string UserName {
get;
set;
}
[Required(ErrorMessage = "密碼必須填寫!")]
[DisplayName("密碼:")]
[DataType(DataType.Password)]
public string Password {
get;
set;
}
[Required(ErrorMessage = "郵箱必須填寫")]
[RegularExpression("", ErrorMessage = "郵件格式不正確!")]
[DisplayName("郵箱:")]
public string Email {
get;
set;
}
[Range(0, 100, ErrorMessage = "年齡必須在1~100之間!")]
[DisplayName("年齡:")]
[DefaultValue(20)]
public int Age {
get;
set;
}
}
2、在 View 中添加下面的代碼,除了要使用 ExtJS 的腳本之外, 與普通的 View 沒有什么區別, 代碼如下:
;ExtJS 實現 ASP.NET MVC 2 客戶端驗證
<% Html.EnableClientValidation(); %>; <%= Html.ValidationSummary(true, "輸入信息不完整,無法完成注冊。") %> <% using (Html.BeginForm()) { %> <%= Html.EditorForModel() %> <% } %>;
運行效果如下圖所示:
如果要做擴展自定義驗證的話,需要做完成下面兩部分:
1、參考 msdn 文檔,添加服務端驗證擴展, 代碼如下:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class CustomAttribute : ValidationAttribute {
public override bool IsValid(object value) {
var val = value as string;
if (string.IsNullOrEmpty(val)) {
return false;
}
return val.Equals("Hello,world!", StringComparison.OrdinalIgnoreCase);
}
}
public class CustomValidator : DataAnnotationsModelValidator {
public CustomValidator(ModelMetadata metadata, ControllerContext context, CustomAttribute attribute)
: base(metadata, context, attribute) {
}
public override IEnumerable GetClientValidationRules() {
return new[] {
new ModelClientValidationRule {
ErrorMessage = "輸入: Hello,world!",
ValidationType = "custom"
}
};
}
}
2、添加對應的客戶端驗證實現,代碼如下:
Ext.apply(Ext.ux.mvc.VTypes, {
custom: function(val, param) {
return val.toLowerCase() == 'hello,world!';
}
});
3、在 Model 上添加屬性,使用擴展驗證,代碼如下:
4、在 App_Start 注冊該擴展,代碼如下:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomAttribute), typeof(CustomValidator));
5、添加擴展之后的運行效果如下圖:

如果你工作中也用到了 ExtJS 和 ASP.NET MVC 2 的話,可以下載這個文件來嘗試一下。
張志敏所有文章遵循創作共用版權協議,要求署名、非商業 、保持一致。在滿足創作共用版權協議的基礎上可以轉載,但請以超鏈接形式注明出處。
本博客已經遷移到 GitHub , 圍觀地址: https://beginor.github.io/
浙公網安備 33010602011771號