[英]MVC client side validation for PhoneAttribute
我有一個模型:
public class MyModel{
[Phone]
public string MyTel { get; set; }
}
在視圖中:
@model MyModel
@Html.EditorFor(x => x.MyTel)
生成的 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"/>
MyTel 字段的客戶端驗證不起作用。 如何使這項工作?
以文章為 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");
}
我在我的 PhoneAttribute 項目中應用的最簡單的解決方案:
第 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; }
}
第二步:添加這兩個庫
<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>
第 3 步:在 web.config 下的 appSettings 添加
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
注意:不要混淆 mvc html helper 和 raw html,它可能會禁用客戶端驗證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.