Check if input in textbox is email - c#

I am trying to validate if the userinput is an email adress (adding a member to database).
The user will enter data in TextBox, when the validating event gets called; I want to check if the input is a valid email adress. So consisting of atleast an # and a dot(.) in the string.
Is there any way to do this through code, or perhaps with a Mask from the MaskedTextbox?

Don't bother with Regex. It's a Bad Idea.
I normally never use exceptions to control flow in the program, but personally, in this instance, I prefer to let the experts who created the MailAddress class do the work for me:
try
{
var test = new MailAddress("");
}
catch (FormatException ex)
{
// wrong format for email
}

Do not use a regular expression, it misses so many cases it's not even funny, and besides smarter people that us have come before to solve this problem.
using System.ComponentModel.DataAnnotations;
public class TestModel{
[EmailAddress]
public string Email { get; set; }
}

Regex for simple email match:
#"\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b"
Regex for RFC 2822 standard email match:
#"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"

See: How to: Verify that Strings Are in Valid Email Format - MSDN
The Regex you are looking should be:
"^(?("")(""[^""]+?""#)|(([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,24}))$"
(From the same source)

I recommend you use this way and it's working well for me.
Regex reg = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (!reg.IsMatch(txtEmail.Text))
{
// Email is not valid
}

I suggest that you use a Regular Expression like:
#"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
To validate the input of your textbox.
Example code:
private void button1_Click(object sender, EventArgs e)
{
Regex emailRegex = new Regex(#"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?
^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+
[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
if (emailRegex.IsMatch(textBox1.Text))
{
MessageBox.Show(textBox1.Text + "matches the expected format.", "Attention");
}
}
Edit: I found a better, more comprehensive Regex.

Related

Mailkit: Could I get the original sender from a forwarded e-mail?

I'm managing forwarded e-mails and noting that if I perform a TextSearchQuery(SearchTerm.FromContains, "test#test.com") I just get the UniqueIds of the forwarder, not the original sender of the e-mail.
I know I could dive into the TextBody or the HtmlBody and look at the "from", but this could vary depending on the language of the client and so on, so I was wondering if is there any method to perform that "deep SearchQuery".
There are so many SearchTerm but a SearchTerm.OriginalFromContains could be interesting, if it doesn't exists yet!
Thanks.
It's not a fire-proof solution but I actually search for all the "mailTo"s on the e-mail, I list them and I give the user the option to exclude a concrete domain of the list.
I finally pick up the last mailTo.
private string ExtractMailTo(string html, string domainToExclude)
{
try
{ //Searches for mailTos with regEx
//If user didn't pass any domain we will just ignore it
//and pick up the last mailTo.
bool deleteDomainUser = (!string.IsNullOrEmpty(domainToExclude)
|| !string.IsNullOrWhiteSpace(domainToExclude));
var mailTos = new List<String>();
string pattern = #"mailto\s*:\s*([^""'>]*)";
foreach (Match match in Regex.Matches(html, pattern))
mailTos.Add(match.Groups[1].Value);
if(deleteDomainUser)
//We search for the domain concreted by the user
//and we delete it from the mailTos List
mailTos.RemoveAll(doms => doms.Contains(domainToExclude));
var last = mailTos.Last();
return last;
}
catch (Exception ex)
{
string message = "A problem ocurred parsing the e-mail body searching for MailTos. \n"
+ ex.Message;
throw new Exception(message, ex);
}
}
Hope it helps somebody.
There's no way to do what you want as IMAP does not support it. MailKit's search API's are limited to the search capabilities of the IMAP protocol (which, unfortunately, are rather limited).
Previous answers are ok, but none of them will give us senders. Same as #Gonzo345 in last answer we can find emails in message.HtmlBody. My solution:
string afterFromPattern = #"From:.*(\n|\r|\r\n)";
string emailPattern = #"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
foreach (Match match in Regex.Matches(message.HtmlBody, afterFromPattern))
{
fromEmail = Regex.Match(match.Value, emailPattern).Value.ToLower();
if (string.IsNullOrEmpty(fromEmail))
{
continue;
}
fromEmails.Add(fromEmail);
}

Selenium entering invalid text (Half text) in text box

While running multiple test cases, selenium is entering invalid text as shown in the attachment.
Below are the two Examples showing the error:
Instead of entering AutomationTest123_6035633258972, it just enters 6035633258972. .
Instead of Entering AutomationTest123_636010703068635512, it just
enters utomationTest123_636010703068635512. .
Code
//StaticVariable is class which has static values
var username = StaticVariable.username;
var password = StaticVariable.password;
driver.FindElement(By.Id("username")).SendKeys(username); //putting wrong values
driver.FindElement(By.Id("password")).SendKeys(password); //putting wrong values
driver.FindElement(By.Id("login")).Click();
Can anyone help me on this? Any help would appreciated.
first of all make sure that
var username = StaticVariable.username;
is assigning the right value.
use a
print
to check what the value of username after assign.
than try by using the below code:
driver.FindElement(By.Id("username")).click()
driver.FindElement(By.Id("username")).clear()
driver.FindElement(By.Id("username")).SendKeys(username);
There can be a couple of reasons I've seen that this can be an issue. I'd first try to clear out the text input first and make sure it has focus.
var username = StaticVariable.username;
var password = StaticVariable.password;
// Fill out user name
var userElem = driver.findElement(By.id("username"));
userElem.click();
userElem.clear();
userElem.sendKeys(userName);
// Fill out password
var passElem = driver.findElement(By.id("password"));
passElem.click();
passElem.clear();
passElem.sendKeys(password);
// Click login button
driver.findElement(By.id("login"))
.click();
If, however, that doesn't fix it, I've had situations where splitting the string up and sending keys a few at a time has worked. That does have a performance penalty so I wouldn't do it unless you really really need to.
public void fooTest() {
// Do stuff to get to the correct page, etc
var username = StaticVariable.username;
var password = StaticVariable.password;
// Fill out user name
var userElem = driver.findElement(By.id("username"));
sendKeys(userElem, userName);
// Fill out password
var passElem = driver.findElement(By.id("password"));
sendKeys(passElem, password);
// Click login button
driver.findElement(By.id("login"))
.click();
// do assertions, etc
}
private void sendKeys(WebElement elem, String keys) {
elem.click();
elem.clear();
for (int i = 0; i < keys.length(); i) {
elem.sendKeys(keys.charAt(i));
}
}
Note : sorry for any syntax / c# errors, I've barely used the language ... I'm much more familiar with Java ;-)
Use the clear method then type the text: driver.findElement(By.cssSelector("").clear();
It may help.
Rather than using 'var' , you might want to try putting in the specific type , such as 'string'. The problem has to be in what is being passed to .SendKeys() or how it is being received by the function.
string username = StaticVariable.username;
string password = StaticVariable.password;

Regex email code not matching. C# visual studio 2010

I am new to c# and Ive come across something I can't fix.
situation
I am creating a windows form application using visual studio 2010 which has the option to validate an email address. I looked at tutorials on using RegularExpressions and have came to this. I feel I'm missing something because every time I validate, it only sends the MessageBox.Show("Email invalid"); to the user.
code
private void validateBtn_Click(object sender, EventArgs e)
{
Regex email = new Regex("^[a-zA-Z0-9]{1-20}#[a-zA-Z0-9]{1-20}.[a-zA-Z]{2-3}$");
if (!email.IsMatch(emailTxt.Text))
{
MessageBox.Show("Email invalid");
}
else
MessageBox.Show("Email Valid");
}
Normally I would never use an Exception to direct program logic like this, but when validating emails I've found using built-in .NET functionality to be more reliable and readable than trying to use Regex to validate an email address.
using (var mm = new MailMessage())
{
try
{
mm.To.Add(emailTxt.Text);
MessageBox.Show("Email Valid");
... rest of your code to send the email
}
catch (FormatException)
{
MessageBox.Show("Email Invalid");
}
}
Alternatively, to just test the address:
try
{
var mail = new MailAddress(emailTxt.Text);
MessageBox.Show("Email Valid");
}
catch (FormatException)
{
MessageBox.Show("Email Invalid");
}
This class is not perfect, and you can find posts showing it doesn't catch every edge case.
But when this is the alternative, I think I'd rather stick with the above and take my chances.
. is a special character, use
Regex email = new Regex(#"^[a-zA-Z0-9]{1-20}#[a-zA-Z0-9]{1-20}\.[a-zA-Z]{2-3}$");
please note I added a '#' in front of the string to avoid escaping the '\'
You have two syntax errors in your regex:
. stands for a random sign, so it must be escaped with a backslash: \. .
{1-20} musst be written with comma: {1,20}.
[a-zA-Z0-9]{1,20}#[a-zA-Z0-9]{1,20}\.[a-zA-Z]{2,3}
works.
if you use C# you have to bring a # before the first " to say it that it should not use backslashes in the string to escape. It should do this when searching for regex.
#"[a-zA-Z0-9]{1,20}#[a-zA-Z0-9]{1,20}\.[a-zA-Z]{2,3} "

RegularExpression validation not working on model

I have the following code:
public class Register
{
[RegularExpression(#"^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$", ErrorMessage = "eMail is not in proper format")]
[Required(ErrorMessageResourceName="Name Required"), ErrorMessageResourceType = typeof(ErrorMessages))]
public string Email{ get; set; }
}
Email that i tried: asd#asd.com is valid but it fail the validation.
The required is working, but the regular expression is failing. Even if I enter a valid email address, it will still say that email is not in proper format.
Anything I missed here? Thanks in advance!
EDIT
This regex validator is working on my other mvc application by using Resources.resx. So I think what is wrong here is how I declared it on my model class.
Regex regx = new Regex(#"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
+ #"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
+ #"#[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$");
/* declare in public and validate for your mail text box */
This is solved. I accidentally put the wrong regex on my code:
"^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$
instead of:
#"^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$
Now I will focus on to make the best email regex. Thanks!

Validate folder name in C#

I need to validate a folder name in c#.
I have tried the following regex :
^(.*?/|.*?\\)?([^\./|^\.\\]+)(?:\.([^\\]*)|)$
but it fails and I also tried using GetInvalidPathChars().
It fails when i try using P:\abc as a folder name i.e Driveletter:\foldername
Can anyone suggest why?
You could do that in this way (using System.IO.Path.InvalidPathChars constant):
bool IsValidFilename(string testName)
{
Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");
if (containsABadCharacter.IsMatch(testName) { return false; };
// other checks for UNC, drive-path format, etc
return true;
}
[edit]
If you want a regular expression that validates a folder path, then you could use this one:
Regex regex = new Regex("^([a-zA-Z]:)?(\\\\[^<>:\"/\\\\|?*]+)+\\\\?$");
[edit 2]
I've remembered one tricky thing that lets you check if the path is correct:
var invalidPathChars = Path.GetInvalidPathChars(path)
or (for files):
var invalidFileNameChars = Path.GetInvalidFileNameChars(fileName)
Validating a folder name correctly can be quite a mission. See my blog post Taking data binding, validation and MVVM to the next level - part 2.
Don't be fooled by the title, it's about validating file system paths, and it illustrates some of the complexities involved in using the methods provided in the .Net framework. While you may want to use a regex, it isn't the most reliable way to do the job.
this is regex you should use :
Regex regex = new Regex("^([a-zA-Z0-9][^*/><?\"|:]*)$");
if (!regex.IsMatch(txtFolderName.Text))
{
MessageBox.Show(this, "Folder fail", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
metrotxtFolderName.Focus();
}

Categories