Use a regular expression validator with your view model property. This regex will match “(999) 999-9999” and anything after. The input will be restricted with jquery.maskedinput to only accept valid numbers. Whether the user enters an extension or not, the regex will still get validated. We only need to valid the minimum required phone number.
Using the Data Annotation on your view model will allow the client side unobtrusive validation to work when the user enters in a phone number with the optional extension.
View Model property
[Required] [DataType(DataType.PhoneNumber)] [RegularExpression(@"^([(][0-9]{3}[)][ ][0-9]{3}[-][0-9]{4})(.*)$", ErrorMessage = "Phone number busted.")] [DisplayName("Contact Phone Number")] public string ContactPhoneNumber { get; set; }
In your view
<div> @Html.EditorFor(x => x.ContactPhoneNumber) @Html.ValidationMessageFor(x => x.ContactPhoneNumber) </div>
Script:
if ($("input[type=tel").length > 0) { $("input[type=tel").mask("(999) 999-9999? ext.9999", { placeholder: " " }); // @Html.EditorFor is used to render any inputs that need the html 5 type attributes. // But @Html.EditorFor, won't allow you to add a css class, so we do it here. $('input[type=text],input[type=tel],input[type=datetime],input[type=date],input[type=number],input[type=password],textarea,input[type=email],input[type=url],input[type=zip]').each(function (idx, item) { if (!$(item).hasClass('form-control')) //class only for Bootstrap styling $(item).addClass('form-control'); }); }