?
Solved

Check if string contains @

Posted on 2006-07-04
8
Medium Priority
?
410 Views
Last Modified: 2012-06-27
Hello Experts,

How do I check if a string is an email address or not

Thanks
0
Comment
Question by:claracruz
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 17035898
use this javascript function

 function isValidEmailId(elm)
   {
       var id=document.getElementById(elm);
       var string = id.value;
            if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
            {
                  return true;
            }
            else
            {
                  alert("Email address is not valid ! ");
                  id.focus();
                  id.select();
                  return false;
            }
   }

hope it helps u :)]thanx
0
 
LVL 10

Expert Comment

by:orbulat
ID: 17035899
u can use regularexpression validator,  or use System.Text.RegularExpression
example of regularexpression validator from http://forums.asp.net/thread/1054492.aspx

<p>
            <asp:TextBox id="TextBox1" runat="server">
            </asp:TextBox>
           
            <asp:Button id="Button1" runat="server"
            Text="Click here">
            </asp:Button>
        </p>
        <p>
            <asp:RegularExpressionValidator
            id="RegularExpressionValidator1"
            runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
            ErrorMessage="Please enter a valid E-mail ID"
            ControlToValidate="TextBox1">
            </asp:RegularExpressionValidator>
        </p>
0
 
LVL 43

Assisted Solution

by:TimCottee
TimCottee earned 400 total points
ID: 17035910
Hi claracruz,

The answer to the initial question is

If MyString.IndexOf("@") > 0 Then
    'It contains @

Now as for checking for an email address then regular expressions are the way to go:

        Dim re As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})")
        If re.IsMatch(TextBox1.Text) Then
            Label2.Text = "Valid"
        Else
            Label2.Text = "Invalid"
        End If

Will use regular expressions to match string against a valid pattern for email addresses.

Tim Cottee
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 6

Expert Comment

by:Nandakumar Sakthivel
ID: 17035953
Hi,
   function isValidEmail(emailaddr)
            {
                  var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
                  if (filter.test(emailaddr))
                  {      
                      return true;
                  }
                  else
                  {
                        return false;
                  }
            }

Can use this function also it will return whether the emaila ddress i s valid or not

Nanda
0
 
LVL 4

Author Comment

by:claracruz
ID: 17035970
Thanx guys,


hOW WOULD i DO THIS BIT IN C#

If MyString.IndexOf("@") > 0 Then
    'It contains @
0
 
LVL 7

Expert Comment

by:pradeepsudharsan
ID: 17036043
var emailAddress='test@texs...com';
var regexp;
 var retval;
regexp=new RegExp(/^[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]$/);
retval=emailAddress.match(regexp);
 if(retval==null)
         {
                   alert("invalid email address ");                   
                        
       }
else
{
      alert("valid email address ");                 
}

in c#
--------------
public void TestEmailRegex()
{
   string patternLenient = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
   Regex reLenient = new Regex(patternLenient);
   string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
      + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
      + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
      + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
      + @"[a-zA-Z]{2,}))$";
   Regex reStrict = new Regex(patternStrict);

   ArrayList samples = new ArrayList();
   samples.Add("joe");
   samples.Add("joe@home");
   samples.Add("a@b.c");
   samples.Add("joe@home.com");
   samples.Add("joe.bob@home.com");
   samples.Add("joe-bob[at]home.com");
   samples.Add("joe@his.home.com");
   samples.Add("joe@his.home.place");
   samples.Add("joe@home.org");
   samples.Add("joe@joebob.name");
   samples.Add("joe.@bob.com");
   samples.Add(".joe@bob.com");
   samples.Add("joe<>bob@bob.come");
   samples.Add("joe&bob@bob.com");
   samples.Add("~joe@bob.com");
   samples.Add("joe$@bob.com");
   samples.Add("joe+bob@bob.com");
   samples.Add("o'reilly@there.com");

   string output = "<table border=1>";
   output += "<tr><td><b>Email</b></td><td><b>Pattern</b>"
      + "</td><td><b>Valid Email?</b></td></tr>";
   bool toggle = true;
   foreach (string sample in samples)
   {
      string bgcol = "white";
      if (toggle)
         bgcol = "gainsboro";
      toggle = !toggle;

      bool isLenientMatch = reLenient.IsMatch(sample);
      if (isLenientMatch)
         output += "<tr bgcolor=" + bgcol + "><td>"
            + sample + "</td><td>Lenient</td><td>Is Valid</td></tr>";
      else
         output += "<tr bgcolor=" + bgcol + "><td>"
            + sample + "</td><td>Lenient</td><td>Is NOT Valid</td></tr>";

      bool isStrictMatch = reStrict.IsMatch(sample);
      if (isStrictMatch)
         output += "<tr bgcolor=" + bgcol + "><td>"
            + sample + "</td><td>Strict</td><td>Is Valid</td></tr>";
      else
         output += "<tr bgcolor=" + bgcol + "><td>"
            + sample + "</td><td>Strict</td><td>Is NOT Valid</td></tr>";

   }
   output += "</table>";

   lblOutput.Text = output;

}

0
 
LVL 6

Expert Comment

by:Nandakumar Sakthivel
ID: 17036057
Hi,
    Include the name space "System.Text.RegularExpressions" in ur page
 
    Private Sub MyValidatingCode()
        ' Confirm there is text in the control.
        If TextBox1.Text.Length = 0 Then
            Throw New Exception("Email address is a required field")
        Else
            If Not Regex.IsMatch(TextBox1.Text, "\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*") Then
                MsgBox("Invalid emailid")
            End If
        End If
    End Sub

The above function will validate for the email id

Thanks,
NAnda
0
 
LVL 12

Accepted Solution

by:
UnexplainedWays earned 600 total points
ID: 17036059
public bool CheckForAtSymbol(string theString)
{
    int index = theString.IndexOf('@');
    return (index >= 0);
}

CheckForAtSymbol("aaa@aaa");
CheckForAtSymbol("aaabaaa");
CheckForAtSymbol("@aaaaaa");

0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month14 days, 12 hours left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question