houman_ag houman_ag - 8 months ago 91
ASP.NET (C#) Question

How to add a blank space character to regular expression

I am using asp.net (c#) and for validation of an email address field, I have the following regular expression:

[RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"]


This works just fine except that when any leading/trailing white spaces are added to the email field, it throws an error as invalid email. How can I modify the regular expression in a way that it would accept such white spaces (later on in my code, I'll remove any spaces from either side so I store valid emails)? Thanks

Answer Source

This doesn't sound right to allow spaces and you will trim off later, the regex is helping that scenario and providing that validation (although you should still check server side)

I think adding (\\s*) at the beginning and end should help you though. i.e.

[RegularExpression("^(\\s*)[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}(\\s*)$")]

This is saying start or ends with whitespace

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download