5

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?

Sparky
  • 98,165
  • 25
  • 199
  • 285
Charlie
  • 1,265
  • 15
  • 18

2 Answers2

8

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");
}
Charlie
  • 1,265
  • 15
  • 18
  • Thanks. One comment: I don't think the `if (this.optional(...))` check should be here. If it's required, there should also be a `[Required]` attribute on the property. The way this code is now, validation will never occur for a non-required property, which is most likely not what one would expect. Please correct me if I'm wrong! – Josh M. Dec 09 '15 at 13:22
  • 2
    This regex does not work correctly. For example, `123` passes this test when it shouldn't. I ended up combining your solution with this one: http://stackoverflow.com/a/4338631/374198 – Josh M. Dec 09 '15 at 13:49
1

The easiest solution I applied in my project for PhoneAttribute :

Step 1: add these annotations

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

 <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.

Mahmud
  • 369
  • 4
  • 13