EvilDr
EvilDr

Reputation: 9580

RegEx stops working when placed into ValidationExpression

I have a text box where a user enters their email address. I need to prevent people using certain email addresses, as this is for corporate (B2B) use.

Can anyone help me with the RegEx which would return false if email addresses contain @gmail or @yahoo?

So far I have this (thanks to @Sabuj) @(yahoo|gmail)\. but when placed into a RegularExpressionValidator it doesn't work:

<asp:RegularExpressionValidator ValidationExpression='@(yahoo|gmail)\.' runat="server" ControlToValidate="txt_email" />

Having read MSDN for more info, I've also tried this but it still returns true regardless of the content entered:

<asp:RegularExpressionValidator ValidationExpression='^(@(yahoo|gmail)\.)$' runat="server" ControlToValidate="txt_email"  />

Upvotes: 0

Views: 221

Answers (4)

Amit Joki
Amit Joki

Reputation: 59252

Use this:

<asp:RegularExpressionValidator ValidationExpression=".*@(?!(yahoo|gmail)).*" ControlToValidate="txt_email" runat="server" ErrorMessage="Yahoo and Gmail disallowed"></asp:RegularExpressionValidator>

The validation expression property should be set to match the entire string.

But my regex .*@(?!(yahoo|gmail)).* matches the whole email. So it works :)

You don't need ^ or $ since the string is gonna be a single line.

Also don't forget to add type="email" to your txt_email. It will automatically take care of whether it is a valid email or not.

If the error msg appears, then it isn't valid, but if it doesn't appear, then it is absolutely valid.

Upvotes: 2

SilverlightFox
SilverlightFox

Reputation: 33538

I've come up with ^.*@(?!(yahoo|gmail)).*$

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="^.*@(?!(yahoo|gmail)).*$" runat="server" ControlToValidate="txt_email" Text="No free email accounts allowed" />

This will allow any text to pass the validator that doesn't contain @yahoo or @gmail.

Don't forget to check Page.IsValid in your code behind, and to include an <asp:ValidationSummary runat="server" /> in your .aspx.

Upvotes: 1

Biffen
Biffen

Reputation: 6354

Since e-mail addresses have a complex syntax (more complex than most people realise, for instance, they can contain comments [RFC 822 § 3.4.3]), I'd suggest not using regex at all for this. Instead, use a "proper" e-mail parser, then ask the parser for the domain part of the address.

Upvotes: 2

Sabuj Hassan
Sabuj Hassan

Reputation: 39375

You can use this regex to check whether the mentioned emails are containing or not:

@(gmail|yahoo|mailinator|guerrillamail|dispostable)\.

Upvotes: 1

Related Questions