PhoneAttribute的MVC客户端验证

时间:2014-04-25 20:31:34

标签: javascript asp.net-mvc forms data-annotations unobtrusive-validation

我有一个模特:

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字段的客户端验证无效。如何使这项工作?

2 个答案:

答案 0 :(得分:8)

以文章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");
}

答案 1 :(得分:0)

我在我的项目中为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; }
} 

第2步:添加这两个库

<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"/>