我在ASP.NET MVC4项目中使用数据注释来对电子邮件和电话字段执行客户端验证 . 电子邮件在客户端成功验证但电话没有 - 它允许我输入无效字符,仅在提交表单时警告我(而不是在输入字符后立即)
在模型中:
[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[Display(Name = "Email")]
public string Email{ get; set; }
[Required(ErrorMessage = "Mobile is required")]
[DataType(DataType.PhoneNumber)]
[Phone]
[Display(Name = "Mobile number")]
public string Mobile { get; set; }
在视图中我相信我包含了正确的脚本参考:
<script type="text/javascript" src="~/Scripts/jquery.validate.min.js" ></script
<script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.min.js" ></script>
..并使用html助手(我正在使用TextBoxFor而不是EditorFor,因为我正在应用类属性,为清楚起见,我省略了这些属性)
@Html.LabelFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
@Html.TextBoxFor(model => model.Email, new { @type = "email" })
@Html.LabelFor(model => model.Mobile)
@Html.ValidationMessageFor(model => model.Mobile)
@Html.TextBoxFor(model => model.Mobile, new { @type = "phone" })
我错过了什么?
4 回答
MVC 4有一个用于EmailAddress的内置显示模板,但没有PhoneNumber . 您需要为
[DataType(DataType.PhoneNumber)]
创建自定义DisplayTemplate .添加以下文件(您可能必须创建子文件夹DisplayTemplates):
Views\Shared\DisplayTemplates\PhoneNumber.cshtml
使用EditorForForted TextBoxFor for Email,然后它会在电子邮件字段中给出错误ok keyup .
它将匹配数字,如:0123456789,012-345-6789,(012)-345-6789等 .
我认为问题是手机类型不受支持 . 见phone type support at w3schools