Oasik Oasik - 2 months ago 15
C# Question

ASP.NET MVC Data annotation validator for email or phone

I am working on a form registration for

ApplicationUser
. There, I have a field
Email or phone
like Facebook. I am using
DataAnnotation
for model validation. In
Data annotation
I get
[EmailAddress]
for email validation and
[Phone]
for phone number validation. But I need something like
[EmailAddressOrPhone]
. So how I can achieve that?

public class RegisterViewModel
{
.....

[Required]
[Display(Name = "Email or Phone")]
public string EmailOrPhone { get; set; }

......
}

Answer

You can achieve this using Regex

public class RegisterViewModel
{
    [Required]
    [Display(Name = "Email or Phone")]
    [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$|^\+?\d{0,2}\-?\d{4,5}\-?\d{5,6}", ErrorMessage = "Please enter a valid email address or phone number")]      
    public string EmailOrPhone { get; set; }
}

Or You can create a custom attribute

 public class EmailOrPhoneAttribute : RegularExpressionAttribute
 {
    public EmailOrPhoneAttribute()
        : base(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$|^\+?\d{0,2}\-?\d{4,5}\-?\d{5,6}")
    {
        ErrorMessage = "Please provide a valid email address or phone number";
    }
 }

and use that

 public class RegisterViewModel
 {
    [Required]
    [Display(Name = "Email or Phone")]
    [EmailOrPhone]    
    public string EmailOrPhone { get; set; }
 }