我有一个模型:
public class MyModel{
[Phone]
public string MyTel { get; set; }
}
在 View 中:
@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字段的客户端验证不起作用。如何使这项工作?
最佳答案
由文章Adding Client-Side Validation Support for PhoneAttribute or Fighting the Lookbehind in JavaScript指导
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");
}
关于javascript - MVC客户端对PhoneAttribute的验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23302488/