I'm validating input in a asp.net page but the problem is it validates e-mails like hasangürsoy#şşıı.com
My code is:
if (Regex.IsMatch(email, #"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"))
{ valid }
else { invalid }
EDIT:
I've written a question before especially to validate e-mail addresses including Turkish characters but now I don't want users to be able to input mails with Turkish characters because users mostly type Turkish characters by mistake and I cannot send mails to these addresses.
Why don't you just use build-in System.Net.Mail.MailAddress class for email validation?
bool isValidEmail = false;
try
{
var email = new MailAddress("hasangürsoy#şşıı.com");
isValidEmail = true;
{
catch (FormatException x)
{
// gets "An invalid character was found in the mail header: '.'."
}
RFC3692 goes into great detail about how to properly validate e-mail addresses, which currently only correctly handle ASCII characters. However this is due to change, and hence your validation should be as relaxed as possible.
I would likely use an expression such as:
.+#.+
which would ensure you're not turning people away because your regular expression gives them no choice.
If the e-mail is important you should be following it up with verification usually done via sending an e-mail to the supplied address containing a link.
I recommend you reading this:
http://www.codeproject.com/KB/validation/Valid_Email_Addresses.aspx
Related
I am using the asp.net validation control to validate email addresses. There was an issue with an email address because it has the following characters. "-." For example the email address w.-a.wsdf.com will not validate due to the ".-" in it. I was looking around for email standards that forbid this but could not find any. Should I change the asp.net regex to a custom one to allow this or is this not a valid email address?
The regex i am using now is : \w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*
You'll get loads of answers for this. This one has always served me well:
/\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
Originally found it in Michael Hartl's Rails book
^[a-zA-Z][\w\.-]*[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$
Regular expressions are great but, as my comments showed in other answers, validating email addresses with them is not an easy task at all.
Based on my experience, I would suggest to either:
stick to the simplest email validation regex, ^.+#.+$ and send a confirmation email with an activation link;
or
avoid using regular expressions at all and use a library like my EmailVerify for .NET, which exposes a custom, fine tuned finite state machine for validating email addresses according to (all of) the related IETF standards plus disposable, DNS, SMTP, mailbox tests.
Obviously you can mix the two alternatives and perhaps avoid using regular expressions but send a confirmation link anyway.
Disclaimer: I am the tech lead of EmailVerify for .NET, a Microsoft .NET component for validating email addresses.
The regex below forbids w.-a.wsdf.com
using System.Text.RegularExpressions;
public static bool IsValidEmail(string email)
{
return Regex.IsMatch(email, #"\A[a-z0-9]+([-._][a-z0-9]+)*#([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z")
&& Regex.IsMatch(email, #"^(?=.{1,64}#.{4,64}$)(?=.{6,100}$).*");
}
See validate email address using regular expression in C#.
Take a text input in html and a button input like this
Now when the button is clicked then the JavaScript function SubmitFunction() will be called. Now write the bellow code in this function.
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
*its works *
I am using the RegEx "^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+[.])*(\.[a-zA-Z]{2,17})$"to validate Email but my lead want to validate as per the Microsoft standard. SO i need to follow
http://msdn.microsoft.com/en-us/library/01escwtf(v=vs.100).aspx
In that everything working fine as per the standard but still i am facing the issues with
Valid: js#internal#proseware.com
Valid: j_9#[129.126.118.1]
the above mentioned mail ID is still returning as invalid. I tried using the regex used in that page
^(?("")(""[^""]+?""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$
but i am getting the error in the server page. Though I pasted the expression inside the validation Expression it can't able to accept the characters.
Note : am using ASP.Net validators for validating the email.
Description
To match both of those email addresses in your sample text, I think I would rewrite your expression like this:
[A-Z0-9._%#+-]+#(?:[A-Z0-9.-]+\.[A-Z]{2,4}|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\])
If you're looking to use this to validate a string which may contain only an email then you can add the start/end of string anchors ^ and $.
Example
Live Demo
Sample Text
Valid: js#internal#proseware.com Valid: j_9#[129.126.118.1]
Matches
[0][0] = js#internal#proseware.com
[1][0] = j_9#[129.126.118.1]
I'm generating an e-mail in my website's controller with a link to my website:
"http://" & Request.Url.Authority & "/some-page"
This works when I tested it on my local machine (returns localhost:12345) and in production (returns www.company.com) but 1 person got this as a result:
http://www.company..com/some-page
As you can see there are 2 .. in the domain name. I can't reproduce this error, how is this possible?
Edit: a bit more information
The type of email I'm sending is a plain text email (no HTML or RTF)
The webserver logs show www.company.com as the domain when the problematic request was made
I only received a partial screenshot of the email. I think the email client is Outlook but I see no reason why Outlook would have misinterpreted the link.
It's certainly possible that this person (or malware) has edited the content of this email.
This is actually a problem with how the email is being encoded, see this answer: https://stackoverflow.com/a/6603002/186288. In summary, you should change the encoding to UTF8 to force base-64 encoding of the email, otherwise some email clients can misinterpret the default Content-Transfer-Encoding: Quoted-Printable; encoding and add in extra "."s in URLs that happen to hit a wrap point.
To do this, add this line before you send the email:
mail.BodyEncoding = System.Text.Encoding.UTF8;
I should have tried this sooner with a simple example:
Module Module1
Sub Main()
Dim SomeAddress As New Uri("http://www.example..com/test")
Console.WriteLine(SomeAddress.Authority)
End Sub
End Module
This will throw an exception in the constructor:
System.UriFormatException - Invalid URI: The hostname could not be
parsed
So the customer couldn't have received such an email from my code without editing it.
Why are you using Request.Url.Authority? I suggest you avoid to use it, and use Request.Url.Host. It's better to use Request.Url.Host or Uri class constructor, when consturcting incorrect URI it will throw exception and you can either log it or show error.
Anyway it's hard to predict why one user have got www.company..com Anyway your code with Request.Url.Authority concatenation can not produce it. So maybe error is in other location.
What can cause the error "The specified string is not in the form required for an e-mail address"?
Source code line that causes the error:
msg.To.Add(new MailAddress("txtEmail.Text"));
msg.To.Add(new MailAddress("txtEmail.Text"));
is the problem. txtEmail.Text is not an e-mail address. If that's a text file that's a list of e-mails, you're going to need to open it and read it and pass them in one by one.
If it's referring to a textbox, take the quotes around it off. Like this:
msg.To.Add(new MailAddress(txtEmail.Text));
For me, the problem was using semi-colon(;) to seperate multiple emails.
Once I change it to comma(,) it works.
Hope this helps someone.
The issue on the code above might have occured due to
msg.To.Add(new MailAddress("txtEmail.Text"));
You might be clear that here "txtEmail.Text" appears as a string but not the mailing address to whom the mail is to be send. So code should be replaced with
msg.To.Add(new MailAddress(txtEmail.Text));
and sometimes the error like "The specified string is not in the form required for an e-mail address" might also occur due to use of improper string.As even I faced it.
Basically I was working in email sending task using the ASP.Net. The main issue for me was sending mail to multiple users. Firstly, I retrieved the email address from database and used " ; " so as to separate the multiple email addresses. Because while sending the email to multiple users, in regular basis we use semicolon i.e. " ;"
Everything seemed ok but after compilation I got the error "The specified string is not in the form required for an e-mail address".
After a bit analysis, I came to know that instead of using the " ; " we should use " , " so as to separate multiple email address while sending mails . This is the formatted string for separating the emails.
For Details visit: http://kopila.com.np
Thank you!
both the sender and recipient address need to be a valid email address format. eg. user#domain.com
Hmm, let me see, is it possible that "txtEmail.Text" is not a valid email address? I'm just guessing here, but you might want to remove the quotes from around that to get the actual value in your control...
Guess what the issue was for us?
Trailing spaces. For some reason, when you use a multi-line text box, spaces are added to the front of the string.
When we used Trim on the string, it worked fine.
I had a problem where I was creating the message with the recipient and the sender already in it, but it returned the following error:
The specified string is not in the form required for an e-mail address
The problematic code was as follows:
MailMessage objMsg = new MailMessage(regEmail.Text.ToString(), "me#mysite.com");
I fixed the issue by replacing that code with this:
MailMessage objMsg = new MailMessage();
objMsg.From = new MailAddress(regEmail.Text.ToString());
objMsg.To.Add(new MailAddress("me#mysite.com"));
It is also helpful to use a regular expression validator in your user control to make sure the address is valid, you can use the following code for asp:
<asp:RegularExpressionValidator ID="regex1" ControlToValidate="regEmail" ErrorMessage="Please enter a valid email address" ValidationExpression="^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$" ValidationGroup="regGroup" runat="server" Display="None" SetFocusOnError="True"></asp:RegularExpressionValidator>
Or if you'd prefer to validate the email in C# then you can use this as also stated by S Fadhel Ali:
public static bool IsValidEmail(String Email)
{
if( Email != null && Email != "" )
return Regex.IsMatch(Email, #"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" );
else
return false;
}
It should be in the following format.
Dim myMail As New Net.Mail.MailMessage(New MailAddress(strFrom), New MailAddress(strTo))
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;
}
}