## 2 replies

Last post Feb 22, 2019 08:58 AM by Sherry Chen

• elahi1mahdi

Member

32 Points

127 Posts

### Use Multi Regular Expression For a Property

Hi,
I want get email or phone number in one textbox but how to set regular expression for
phone number and email together ?

``` [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)\$", ErrorMessage = "Please enter a valid e-mail adress")]
[RegularExpression(@"^\(?([0-9]{4})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})\$", ErrorMessage = "incorect phone")]
public string Username { get; set; }```

• yogyogi

Participant

1040 Points

729 Posts

### Re: Use Multi Regular Expression For a Property

You can also use or (|) character to match any one of a series of patterns

`[RegularExpression(@"^(([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))|(\(?([0-9]{4})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4}))\$", ErrorMessage = "incorect phone")] public string Username { get; set; }`

Check this tutorial - Alternation Constructs in Regular Expressions

Helping you always. Don't forget to click "Mark as Answer" on the post that helped you.
ASP.NET Core Tutorials → Start from the Beginning and become an Expert in 30 days time ♠
• Sherry Chen

Participant

1400 Points

427 Posts

### Re: Use Multi Regular Expression For a Property

Feb 22, 2019 08:58 AM|Sherry Chen|LINK

Hi elahi1mahdi ，

Try a custom attribute like below:

EmailOrPhoneAttribute that inherits from ValidationAttribute

```    public class EmailOrPhoneAttribute: ValidationAttribute
{
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{            // the regular expression for email and phone that you want
Regex email = new Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\$");
Regex phone = new Regex(@"^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}\$");
var model = validationContext.ObjectInstance as Customer;

if (model == null)
{
throw new ArgumentException("Attribute not applied on Customer");
}
else
{
if (email.IsMatch(model.CusName)||phone.IsMatch(model.CusName))
{
return ValidationResult.Success;
}
}
return new ValidationResult(GetErrorMessage(validationContext));

}

private string GetErrorMessage(ValidationContext validationContext)
{
// Message that was supplied
if (!string.IsNullOrEmpty(this.ErrorMessage))
return this.ErrorMessage;

// Custom message
return \$"{validationContext.DisplayName} can't be in future";
}
}```

Using [EmailOrPhone] on the property of model

```public class Customer
{
public int Id { get; set; }

public string CusName { get; set; }
public int Age { get; set; }

}```

You could refer to here .

Best Regards,

Sherry

MSDN Community Support