Solved

Check if string contains @

Posted on 2006-07-04
8
400 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
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
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.

 
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: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying 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

Suggested Solutions

Title # Comments Views Activity
ASP.net VB.net Errors when sending data to SQL 5 21
imap read mail 1 34
RLDC Reporting in Visual studio 11 30
Convert Select to DropDownListFor MVC 5 2 30
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…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

837 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