Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 438
Jed Avatar asked May 18 '12 08:05

Jed


People also ask

How validate phone no in asp net?

Phone Number Validation in ASP.NET Core In net core, validation rules are defined in the model. Phone number validation uses the DataAnnotations namespace, which has two validation attributes: DataType and Phone. You should use the DataType in your model class if your MobilePhone field is of a simple type.

What data type should be used for phone numbers in C#?

The DataAnnotations namespace provides two ways of validating a telephone numbers as a data type, enumeration and derived class. Use the enumeration method when your phone number field is a simple type and use the derived class when the field is an object type.


3 Answers

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

like image 24
lucask Avatar answered Oct 22 '22 21:10

lucask


Try this:

[DataType(DataType.PhoneNumber, ErrorMessage = "Provided phone number not valid")]
like image 176
Dikchani Avatar answered Oct 22 '22 23:10

Dikchani


Try for simple regular expression for Mobile No

  [Required (ErrorMessage="Required")]
  [RegularExpression(@"^(\d{10})$", ErrorMessage = "Wrong mobile")]
   public string Mobile { get; set; }
like image 1
kavitha Reddy Avatar answered Oct 22 '22 23:10

kavitha Reddy