Cooper
Cooper

Reputation: 197

Always fails when use the regex

I want to limit emails to those coming from my company only. This is what I have but it always fails:

[Required]
[EmailAddress]
[Display(Name = "Email")]
[RegularExpression(@"/\w+@mycompany\.com/", ErrorMessage = "You must use your mycompany email to register")]
public string Email { get; set; }

This email always returns an error: [email protected]. What am I doing wrong?

Upvotes: 1

Views: 127

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

In C# regex, unlike PHP, JavaScript, and some other languages, you do not have to use delimiters.

[RegularExpression(@"\w+@mycompany\.com", ErrorMessage = "You must use your mycompany email to register")]

The regex is anchored in a RegularExpressionAttribute and it will match a string that

  • \w+ - Starts with alphanumeric, 1 or more occurrences
  • @ - then has a literal @
  • mycompany\.com - and ends with a literal mycompany.com (dot must be escaped to match a literal dot).

Upvotes: 3

Related Questions