3

I'm trying to validate some user contact details like so:

public class Customer
{
    [Display(Name = "Your e-mail :")]
    [Required(ErrorMessage = "An email address is required")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string ContactEmail { get; set; }    

    [Display(Name = "Your contact number :")]
    [Required(ErrorMessage = "A phone number is required")]
    [Phone(ErrorMessage = "Invalid Phone Number")] 
    public string ContactNumber { get; set; }

}

In my view the email validation works great and only allows valid email addresses. However, the phone validation doesn't work at all, it allows all kinds of letters and special characters.

The documentation states that the PhoneAttribute class

Specifies that a data field value is a well-formed phone number using a regular expression for phone numbers

So why is this not happening?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • 1
    I'm agree with Vignesh, don't use default `Phone` data annotation. It never works as we want and the culture as we want. I advice you to create your own, with your own regex – GGO Dec 13 '17 at 13:10
  • Related answer: https://stackoverflow.com/a/22111943/1220550 – Peter B Dec 13 '17 at 13:32
  • is it possible to have the RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture reflected in the string? –  Dec 13 '17 at 13:49

1 Answers1

7

Use following Code for Phone validation.

[Display(Name = "Your contact number :")]
[Required(ErrorMessage = "A phone number is required.")]
[DataType(DataType.PhoneNumber, ErrorMessage = "Invalid Phone Number")]
[RegularExpression(@"^([0-9]{10})$", ErrorMessage = "Invalid Phone Number.")]
public string ContactNumber { get; set; }
  • This is what I ended up doing, it's a shame the PhoneAttribute doesn't work though –  Dec 14 '17 at 15:35