Forum Moderators: open
We would like to allow the user to enter either a single e-mail address into a text field, or an indefinite number of e-mail addresses seperated by commas.
I can easily check that a single e-mail address is correct with the built in regex in Visual Studio, but how can I check to ensure that the text contained within the text field matches a correct pattern and that each item is in a correct format?
For example.
test@example.com (CORRECT)
test@example.com, abc@example.com (CORRECT)
test@test, abc@example.com (NOT CORRECT)
test@example.com abc@example.com (NOT CORRECT)
test@example.com, abc@example.com, (NOT CORRECT)
Any help would be greatly appreciated.
Thanks in advance
[edited by: marcel at 4:07 pm (utc) on Dec. 23, 2009]
[edit reason] examplified [/edit]
- Split the email address string at the comma
- Check each (trimmed) string against the Regular Expression
- Output a string showing all invalid email addresses
- If error string is empty, all email addresses are valid
Here is some example code, quick and dirty, so it needs some tweaking but you get the general idea.
string emails = "info@example.com, me@example.com, me@example";
string[] emailArray = emails.Split(',');
string errors = String.Empty;foreach (string email in emailArray)
{
Regex re = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
Match m = re.Match(email.Trim());
if (!m.Success)
{
errors += String.Format("{0} is not a valid Email address<br />", email.Trim());
}
}
if (!String.IsNullOrEmpty(errors))
{
Response.Write(errors);
return;
}
// else continue
It uses Ajax to check the emails in code behind, giving a 'client side' user experience.
Code for your web page:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
<asp:TextBox ID="txtEmailAddresses" runat="server" Width="500" />
<br />
<span id="emailErrors" runat="server" style="display: none; color: Red;">* One or more emails invalid.</span>
<script type="text/javascript">
var emailTextBox = document.getElementById('<%=txtEmailAddresses.ClientID%>');
var emailErrors = document.getElementById('<%=emailErrors.ClientID%>');
function emailCheck() {
var emails = emailTextBox.value;
PageMethods.emailCheck(emails, emailErrorsCallback);
}
function emailErrorsCallback(result) {
emailErrors.style.display = result ? 'none' : 'inline';
}
$addHandler(emailTextBox, 'blur', emailCheck);
</script>
</form>
and in the code behind:
[WebMethod]
public static bool emailCheck(string emails)
{
string[] emailArray = emails.Split(',');
foreach (string email in emailArray)
{
Regex re = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
Match m = re.Match(email.Trim());
if (!m.Success)
{
return false;
}
}
return true;
}
* Remember to reference the System.Web.Services namespace.
You could also adapt this to return a string, showing all of the invalid email addresses like in my first example.