asp.net validation when field is not required - asp.net

I need to set validation on a textbox where the user types in their email address... This is not a required field though so I want to allow the form to be submitted if the textbox contains the default text ("Email address").
I've posted the code i have already to ensure a valid email address is typed.
<asp:RegularExpressionValidator CssClass="errorpopup" Display="Dynamic" ID="regexpEmail"
ValidationGroup="mySubmit" runat="server" ErrorMessage="<strong>Please enter a valid email address.</strong>"
ControlToValidate="tbEmail" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
SetFocusOnError="true" />

Just enclose the entire regex in (?:...)? to make it optional.
But you're not using a very good e-mail validation regex. Aside from the fact that e-mail addresses can never reliably be validated by regular expressions, you could do a little better by using
^(?:[\w.%+-]+#(?:[\w-]+\.)+[A-Za-z]{2,6}\s*|Email address)?$
This will still not catch all valid addresses, and will match some invalid addresses. But short of the RFC 2822 implementation regex which spans about four or five lines of code, this is probably a good compromise.

Related

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" />
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.
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.
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.
You can use this regex to check whether the mentioned emails are containing or not:
#(gmail|yahoo|mailinator|guerrillamail|dispostable)\.

How to check in an asp text box has # sign

I'm developing a module where I need to take input from a user one of each is users email. In order to filter out a wrong input I want to check if a corresponding checkbox has an # sign.
Does anyone knows how can I check it using vb.net ?
Aside the main question to check if a string contains the # character and considering that you are getting your string from a user input, in your case I think is better to check if the user entered a valid mail address.
To do so there are some solutions all reported in this other SO question How do I validate email address formatting with the .NET Framework?
In ASP.NET you can use RegularExpressionValidator for this.
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server"
ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ControlToValidate="tbEmail"
ErrorMessage="Invalid Email Format">
</asp:RegularExpressionValidator>

Email regular expression validator for allowing whitespace at start and end

Following expression work well for email validation with asp.net but does not allow whitespace at start and end.
^(([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$
Have any way to allow whitespace?
Here is full asp.net markup, I can not trim before validation.
<asp:TextBox ID="txtEmail" runat="server" MaxLength="100" CssClass="textbg text"></asp:TextBox>
<asp:RegularExpressionValidator ID="EmailValidator" runat="server" ErrorMessage="Email is not vaild."
ForeColor="Red" ControlToValidate="txtEmail" ValidationExpression="^(([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$"
ValidationGroup="register">Email is not vaild.</asp:RegularExpressionValidator>
I would echo the previous points suggesting trimming the input prior to validation. Trimming or ignoring whitespace is a pretty common requirement, so I would be very surprised if your validator couldn't handle it.
I would also point out an email address with that spaces on either end is an invalid email address, so passing it as valid is technically incorrect.
However, if it can't trim it, and you must pass it, then it is trivially easy to modify any regex to allow whitespace at either end.
White space is represented in regex with \s. Zero or more white spaces would be \s*.
Therefore, all you need to do is add \s* to the start and end of the expression, immediately inside the^and$` start and end markers, like so:
/^\s*(.......)\s*$/
(where ...... represents an expression to validate an email address (but probably not the one you've quoted in the question).
Hope that helps.
Email validation using regular expressions are not easy. Since you're using ASP.NET, you could just use the same regular expression MailAddress uses. Presumably most email addresses are not going to be invalid, so the Try...Catch operation shouldn't be too expensive.
MailAddress mailAddress;
try
{
mailAddress = new MailAddress(txtEmail.Text);
}
catch (Exception ex)
{
//Email considered invalid
}
Edit 2 - This one should work with the validator:
(\s?)+\w+(([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*(\s?)+
Just be aware, email validation cannot be considered reliable because it's very easy to bypass most of the regular expressions.

Regular expression for e-mail validation not working

I've set up a regular expression validator to validate all e-mail addresses that are entered into a textbox on one of my forms the only problem is it's not working in a weird case.
Here's my code
<asp:TextBox ID="tbEmail1" runat="server" />
<asp:RegularExpressionValidator Display="Dynamic" ID="rgv1" runat="server"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ControlToValidate="tbEmail1" ErrorMessage="Invalid email address" />
The case that this is not working is when an e-mail address is entered like this
jamie-taylor-#hotmail.co.uk
Now I wasn't aware that e-mail addresses could be set up in this way but i've just set one up and it seems to be fine except the fact that I cannot input this into my form without it telling me it's invalid
Any ideas?
Thanks in advance
Comparing E-mail Address Validating Regular Expressions. This page has both regexes and e-mail addresses to test with.
It is generally better to make your regex not very strict. Better to have one or two e-mails bounce back than that your customers can not create an account.
let's enhance the regex :
\w+([-+.']\w+[-]*)*#\w+([-.]\w+)*\.\w+([-.]\w+)*
edit
for #Sjoerd :
\w+([-+.']\w+[-]*)*#\w+([-.]*\w+)*\.\w+([-.]\w+)*
use the below expression may help you
\w+([-+.']\w+[-])*#\w+([-.]\w+)*\.\w+([.]\w+)*

ASP.NET email validator regex

Does anyone know what the regex used by the email validator in ASP.NET is?
Here is the regex for the Internet Email Address using the RegularExpressionValidator in .NET
\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*
By the way if you put a RegularExpressionValidator on the page and go to the design view there is a ValidationExpression field that you can use to choose from a list of expressions provided by .NET. Once you choose the expression you want there is a Validation expression: textbox that holds the regex used for the validator
I don't validate email address format anymore (Ok I check to make sure there is an at sign and a period after that). The reason for this is what says the correctly formatted address is even their email? You should be sending them an email and asking them to click a link or verify a code. This is the only real way to validate an email address is valid and that a person is actually able to recieve email.
E-mail addresses are very difficult to verify correctly with a mere regex. Here is a pretty scary regex that supposedly implements RFC822, chapter 6, the specification of valid e-mail addresses.
Not really an answer, but maybe related to what you're trying to accomplish.
We can use RegularExpressionValidator to validate email address format. You need to specify the regular expression in ValidationExpression property of RegularExpressionValidator. So it will look like
<asp:RegularExpressionValidator ID="validateEmail"
runat="server" ErrorMessage="Invalid email."
ControlToValidate="txtEmail"
ValidationExpression="^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$" />
Also in event handler of button or link you need to check !Page.IsValid.
Check sample code here : sample code
Also if you don't want to use RegularExpressionValidator you can write simple validate method and in that method usinf RegEx class of System.Text.RegularExpressions namespace.
Check example:
example
For regex, I first look at this web site: RegExLib.com
Apart from the client side validation with a Validator, I also recommend doing server side validation as well.
bool isValidEmail(string input)
{
try
{
var email = new System.Net.Mail.MailAddress(input);
return true;
}
catch
{
return false;
}
}

Resources