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.Length > _maxWords)
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
public readonly int _maxWords;
}
使用:
[MaxWords(10,ErrorMessage="too many words")]
public string FisrtName { get; set; }
不起作用为什么?
ValidationAttribute 怎么触发的
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("create","order",FormMethod.Post)
) {
@Html.ValidationSummary(true)
<table>
<tr>
<td>FirstName</td><td>
@Html.EditorFor(m=>m.FisrtName)
@Html.ValidationMessageFor(m=>m.FisrtName)
</td>
@Html.ValidationSummary(true)改为 @Html.ValidationSummary()试试看
btw:你的这个需求,不必要自定义,用标准的StringLength
不知道你是不是想要客户端起作用,那样的话,重写客户端验证即可。