Reputation: 20078
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
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:
@
into the second character class(...)?
(it can also be a non-capturing group, BTW: (?:...)?
)-
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