Solved

Check if string contains @

Posted on 2006-07-04
8
405 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 100 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
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 
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 150 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

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
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…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…

726 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