Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email data annotation validation works but Phone doesn't

I'm using data annotations in my ASP.NET MVC4 project to perform client-side validation on email and phone fields. Email is successfully validating in the client but phone doesn't - it allows me to enter invalid characters and only warns me on submission of the form (rather than immediately after the character is typed)

In the model:

[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[Display(Name = "Email")]
public string Email{ get; set; }

[Required(ErrorMessage = "Mobile is required")]
[DataType(DataType.PhoneNumber)]
[Phone]
[Display(Name = "Mobile number")]
public string Mobile { get; set; }

In the view I believe I'm including the correct script references:

<script type="text/javascript" src="~/Scripts/jquery.validate.min.js" ></script
<script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.min.js" ></script>

..and using html helpers (I'm using TextBoxFor rather than EditorFor as I'm applying class attributes which I have omitted here for clarity)

@Html.LabelFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
@Html.TextBoxFor(model => model.Email, new { @type = "email" })       

@Html.LabelFor(model => model.Mobile)
@Html.ValidationMessageFor(model => model.Mobile)
@Html.TextBoxFor(model => model.Mobile, new { @type = "phone" }) 

What am I missing?

like image 331
Liam Weston Avatar asked Nov 01 '13 12:11

Liam Weston


2 Answers

[Required(ErrorMessage = "Mobile is required")]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered mobile format is not valid.")]
public string Mobile{get; set;}

It will match numbers like: 0123456789, 012-345-6789, (012)-345-6789 etc.

like image 122
Kris1 Avatar answered Nov 05 '22 09:11

Kris1


MVC 4 has a built-in display template for EmailAddress but not PhoneNumber. You need to create a custom DisplayTemplate for [DataType(DataType.PhoneNumber)].

Add the following file (you will likely have to create the subfolder DisplayTemplates):
Views\Shared\DisplayTemplates\PhoneNumber.cshtml

@model System.String
@if (Model != null)
{
    @:@System.Text.RegularExpressions.Regex.Replace(@Model, "(\\d{3})(\\d{3})(\\d{4})", "$1-$2-$3")
}
like image 22
RitchieD Avatar answered Nov 05 '22 11:11

RitchieD