Search code examples
javascriptasp.net-mvcformsdata-annotationsunobtrusive-validation

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:

<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. How to make this work?


Solution

  • Guided by article 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");
    }