我正在尝试通过 Unobtrusive AJAX 表单在 MVC 3 中实现客户端验证。
public class PhoneNumberAttribute : RegularExpressionAttribute, IClientValidatable
{
private const string Message = " must be a valid phone number";
public PhoneNumberAttribute()
: base(@"^[\s\d\+\(\)]+$")
{
ErrorMessage = "{0}" + Message;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new List<ModelClientValidationRule>() {
new ModelClientValidationRule{
ValidationType="phonenumber",
ErrorMessage= metadata.DisplayName + " " + Message
}
};
}
}
模型:
public class MyModel
{
[DisplayName("Phone Number")]
[PhoneNumber]
public string PhoneNumber{ get; set; }
}
HTML
<% using (Ajax.BeginForm("Contact", new AjaxOptions() { UpdateTargetId = "ajaxcontactform",
OnBegin = "ShowProcessing",
OnComplete = "HideProessing",
InsertionMode = InsertionMode.Replace
}))
{%>
<%: Html.ValidationSummary()%>
<%: Html.TextBoxFor(m => m.PhoneNumber, new { Class = "contacttextform" })%>
<input id="sendBtn" name="send" type="submit" class="contactformbutton" value="Send" />
<%}%>
我已经为具有 [Required] 属性以及自定义验证属性的字段包含了必需的 .js 文件和其他客户端验证工作。
请建议为什么它不适用于 PhoneNumber 字段?
谢谢,