ASP.NET MVC 3 Data Annotation for Mobile and Phone Numbers (Edited)

asp.net-mvc-3

Solution

You can use regular expression attribute like so:

namespace PhoneBook.Models
{
    public class Contact
    {
        [Required(ErrorMessage="Telephone Number Required")
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered phone format is not valid.")]
        public string Telephone Number {get; set;}
    }
}

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

You can learn more about this expression here: How to use Regular expression for validating Phone Numbers

Problem

How can I write the validation using data annotation in writing telephone number such as "094-4567" or mobile number such as "09129705678" etc.? ``` using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; namespace PhoneBook.Models { public class Contact { [Required(ErrorMessage="Telephone Number Required") [?] public string Telephone Number {get; set;} } } ``` I really don't know what to do...

Original source