Nick Kahn
Nick Kahn

Reputation: 20078

DataAnnotations validation adding `@` to RegularExpression

How do I add to accept @ along with the RegularExpression I have below?

[StringLength(250)]
[RegularExpression(@"[A-Za-z0-9][A-Za-z0-9\-\.]*|^$", 
ErrorMessage = "DomainName may only contain letters (a-z), digits (0-9), hypens (-) and dots (.), and must start with a letter or digit")]
public string DomainName{ get; set; }

Upvotes: 0

Views: 55

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

Use

^([A-Za-z0-9][[email protected]]*)?$

See regex demo

Here is the regex breakdown:

  • ^ - start of string
  • ([A-Za-z0-9][[email protected]]*)? - 1 or 0 (due to ? greedy quantifier) occurrence of...
    • [A-Za-z0-9] - one ASCII letter followed by...
    • [[email protected]]* - 0 or more characters that are either ASCII letters or digits or literal @/./- symbols.
  • $ end of string.

So, the main points are:

  • adding the @ into the second character class
  • turning the whole expression into an optional group (...)? (it can also be a non-capturing group, BTW: (?:...)?)
  • removing unnecessary escape symbols from the character class (if - is at the start/end of the character class, or as in your regex after a valid range, it does not require escaping).

Upvotes: 1

Related Questions