[英]MVC client side validation for PhoneAttribute
I have a model:我有一个模型:
public class MyModel{
[Phone]
public string MyTel { get; set; }
}
in the view:在视图中:
@model MyModel
@Html.EditorFor(x => x.MyTel)
the HTML generated:生成的 HTML:
<input type="tel" value="" name="MyTel" id="MyTel" data-val-phone="The MyTel field is not a valid phone number." data-val="true" class="text-box single-line"/>
the client side validation for the MyTel field does not working. MyTel 字段的客户端验证不起作用。 How to make this work?
如何使这项工作?
Guided by article Adding Client-Side Validation Support for PhoneAttribute or Fighting the Lookbehind in JavaScript以文章为 PhoneAttribute 添加客户端验证支持或在 JavaScript 中对抗 Lookbehind 为指导
function initPhoneValidator() {
$.validator.addMethod("phone", function (value, element) {
if (this.optional(element)) {
return true;
}
var reverseValue = $.trim(value).split("").reverse().join("");
var reverseRegEx = new RegExp("^(\\d+\\s?(x|\\.txe?)\\s?)?((\\)(\\d+[\\s\\-\\.]?)?\\d+\\(|\\d+)[\\s\\-\\.]?)*(\\)([\\s\\-\\.]?\\d+)?\\d+\\+?\\((?!\\+.*)|\\d+)(\\s?\\+)?$", "i");
var match = reverseRegEx.exec(reverseValue);
return (match && (match.index === 0) && (match[0].length === value.length));
});
$.validator.unobtrusive.adapters.addBool("phone");
}
The easiest solution I applied in my project for PhoneAttribute :我在我的 PhoneAttribute 项目中应用的最简单的解决方案:
Step 1: add these annotations第 1 步:添加这些注释
public class MyModel{
[Required(ErrorMessage = "You must provide a mobile number")]
[Phone]
[MaxLength(13)] //custom maximum length enabled
[MinLength(10)]//custom minimum length enabled
[RegularExpression("^[0-9]*$", ErrorMessage = "mobile number must be
numeric")]
public string MyTel { get; set; }
}
Step 2: add these two libraries第二步:添加这两个库
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js"></script>
Step 3: In Web.config under appSettings add第 3 步:在 web.config 下的 appSettings 添加
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
NB: Don't mix up mvc html helper and raw html it may disable client-side validation.注意:不要混淆 mvc html helper 和 raw html,它可能会禁用客户端验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.