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; }
......
}
You shouldn't use your own regex to validate email addresses, however I personally would be using the following logic to determine if it is a valid email address. If it isn't a valid email address, you can assume it's a phone number.
The following code uses the [EmailAddress]
attribute that you've already mentioned, but within the code. This way you don't have to invent your own way of validating the email address.
public EmailOrPhoneAttribute : ValidationAttribute
{
public override IsValid(object value)
{
var emailOrPhone = value as string;
// Is this a valid email address?
if (this.IsValidEmailAddress(emailOrPhone))
{
// Is valid email address
return true;
}
else if (this.IsValidPhoneNumber(emailOrPhone))
{
// Assume phone number
return true;
}
// Not valid email address or phone
return false;
}
private bool IsValidEmailAddress(string emailToValidate)
{
// Get instance of MVC email validation attribute
var emailAttribute = new EmailAddressAttribute();
return emailAttribute.IsValid(emailOrPhone);
}
private bool IsValidPhoneNumber(string phoneNumberToValidate)
{
// Regualr expression from https://stackoverflow.com/a/8909045/894792 for phone numbers
var regex = new Regex("^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$");
return regex.IsMatch(phoneNumberToValidate)
}
}
Naturally you will need to determine how you are going to determine if the phone number is correct yourself, because phone numbers are different in different countries. I've just taken a regular expression from this question as an example.
You can achieve this using Regex
. You have to combine the regex for email and phone together.
public class RegisterViewModel
{
[Required]
[Display(Name = "Email or Phone")]
/* /<email-pattern>|<phone-pattern>/ */
[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; }
}
In addition to custom attributes, you can have a look to this library: https://github.com/jwaliszko/ExpressiveAnnotations
An example is:
[Required]
[AssertThat("IsEmail(EmailOrPhone) || (Length(EmailOrPhone) > 8 && Length(EmailOrPhone) < 16 && IsRegexMatch(EmailOrPhone, '^\\d+$'))",
ErrorMessageResourceType = typeof (Resources), ErrorMessageResourceName = nameof(Resources.EmailFormatInvalid))]
[Display(Name = "EmailOrPhone")]
public string EmailOrPhone { get; set; }
where I have used AssertThat attribute from ExpressiveAnnotations and created a error message EmailFormatInvalid in a Resources file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With