MVC中利用特性進行數(shù)據(jù)驗證,特性定義在名稱空間System.ComponentModel.DataAnnotations中,它們提供了服務(wù)器端驗證,也支持客戶端驗證。在名稱空間DataAnnotations中。其中包含ErrorMessage的驗證錯誤顯示消息內(nèi)容,我們常用的特性如下:
1、StringLength:它可以確保用戶提供的字符串長度符合數(shù)據(jù)庫模式的要求,可以使大長度,也可以是區(qū)間長度。
2、RegularExpression:通過增則表達試校驗數(shù)據(jù)。
3、Range:數(shù)值類型中范圍驗證。
4、Remote:通過調(diào)用服務(wù)Control來實現(xiàn)服務(wù)驗證內(nèi)容
5、Compare:對比驗證內(nèi)容
6、ReadOnly:只讀類型
7、DisplayFormat:顯示格式
8、ScaffoldColumn:隱藏HTML標簽方法
9、DataType:數(shù)據(jù)類型
我們也可以自定義驗證規(guī)則通過引用using System.ComponentModel.DataAnnotations;
public class MaxWordsAttribute : ValidationAttribute
{
public MaxWordsAttribute(int maxWords)
:base("{0} has too many words.")
{
_maxWords = maxWords;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
if (value != null)
{
var valueAsString = value.ToString();
if (valueAsString.Split(' ').Length > _maxWords)
{
var errorMessage = FormatErrorMessage(
validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
private readonly int _maxWords;
}
通過實現(xiàn)UserAttribute來完成我們的自定義的數(shù)據(jù)驗證規(guī)則。
我們也可以向我們的創(chuàng)建的驗證規(guī)則類中添加錯誤消息規(guī)則,消息可以向基類的構(gòu)造函數(shù)傳遞一個默認的錯誤提示消息。
通過調(diào)用繼承的FormatErrorMessage方法將會自動地使用顯示的屬性名稱來格式化這個字符串。FormatErrorMessage可以確保我們使用正確的錯誤。