Solved

Check if string contains @

Posted on 2006-07-04
8
392 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
 
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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

AJAX ModalPopupExtender has a required property "TargetControlID" which may seem to be very confusing to new users. It means the server control that will be extended by the ModalPopup, for instance, if when you click a button, a ModalPopup displays,…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

707 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now