RegExp to validate an email address

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andrew DeFaria

    #1

    RegExp to validate an email address

    I was reading my O'Reilly JavaScript The Definitive Guide when I came
    across RegExp and thought I could tighten up my JavaScript code that
    checks for a valid email address. Why does the following not appear to work:

    var email_address = "Joe@Schmoe ";
    var email_regex = new RegExp ("^(\\w+)(\@)(\ \w+)(\.)(\\w+)$ ");
    var result = email_regex.exe c (email_address) ;
    alert (" result[1] = \"" + result[1] + "\"\n" +
    " result[2] = \"" + result[2] + "\"\n" +
    " result[3] = \"" + result[3] + "\"\n" +
    " result[4] = \"" + result[4] + "\"\n" +
    " result[5] = \"" + result[5] + "\"");

    The resulting alert box contains:

    result[1] = "Joe"
    result[2] = "@"
    result[3] = "Schm"
    result[4] = "o"
    result[5] = "e"

    It appears that the "\." is not escaping the "." to mean the literal
    period. What am I doing wrong?
    --
    How come you don't ever hear about gruntled employees? And who has been
    dissing them anyhow?

  • Graham J

    #2
    Re: RegExp to validate an email address

    > It appears that the "\." is not escaping the "." to mean the
    literal[color=blue]
    > period. What am I doing wrong?[/color]

    You have "\." when you meant to put "\\." in the RegExp string.

    Comment

    • Thomas 'PointedEars' Lahn

      #3
      Re: RegExp to validate an email address

      Andrew DeFaria wrote:
      [color=blue]
      > [...]
      > var email_regex = new RegExp ("^(\\w+)(\@)(\ \w+)(\.)(\\w+)$ "
      > [...]
      > It appears that the "\." is not escaping the "." to mean the literal
      > period. What am I doing wrong?[/color]

      You did not notice consistently that the backslash is in string literals an
      escape character, too. Therefore you need to escape it with another `\' if
      you want a literal `\' to be passed to the RegExp constructor function, as
      you did before and after. Otherwise it is ignored unless the combination
      with the following character (here: `.') forms a known escape sequence, e.g.
      `\n':

      var email_regex = new RegExp ("^(\\w+)(@)(\\ w+)(\\.)(\\w+)$ "

      But you can use RegExp literals instead which makes the Regular Expression
      more legible since you need not to escape escape characters of strings:

      var email_regex = /^(\w+)(@)(\w+)( \.)(\w+)$/;

      BTW: In JavaScript, `@' need not to be escaped neither in string nor in
      RegExp literals.


      PointedEars

      P.S.:
      | Content-Type: multipart/alternative;
      | boundary="------------020801000303080 605020808"

      Please don't post Multipart HTML, Usenet is (except of
      newsgroups where binaries are accepted) a text-only medium.
      Uncheck Edit, Mail & Newsgroups Account Settings, $News_account,
      Composition and Addressing, Compose messages in HTML format.
      [color=blue]
      > --[/color]

      This preference setting will also make your signature separator
      correct and working.

      Comment

      • Andrew DeFaria

        #4
        Re: RegExp to validate an email address

        Thomas 'PointedEars' Lahn wrote:
        [color=blue]
        > Andrew DeFaria wrote:
        >[color=green]
        >> [...]
        >> var email_regex = new RegExp ("^(\\w+)(\@)(\ \w+)(\.)(\\w+)$ "
        >> [...]
        >> It appears that the "\." is not escaping the "." to mean the literal
        >> period. What am I doing wrong?[/color]
        >
        > You did not notice consistently that the backslash is in string
        > literals a escape character, too. Therefore you need to escape it with
        > another `\' if you want a literal `\' to be passed to the RegExp
        > constructor function, as you did before and after. Otherwise it is
        > ignored unless the combination
        > with the following character (here: `.') forms a known escape
        > sequence, e.g. `\n':
        >
        > var email_regex = new RegExp ("^(\\w+)(@)(\\ w+)(\\.)(\\w+)$ "[/color]

        I had tried that. When I did the the following fails:

        var email_address = "Joe@Schmoe ";
        var email_regex = new RegExp ("^(\\w+)@(\\w+ )(\\.)(\\w+)$") ;
        var result = email_regex.exe c (email_address) ;
        alert ("Checking results");
        alert (" result[0] = \"" + result[0] + "\"");
        alert (" result[1] = \"" + result[1] + "\"");
        alert (" result[2] = \"" + result[2] + "\"");
        alert (" result[3] = \"" + result[3] + "\"");
        alert (" result[4] = \"" + result[4] + "\"");

        I get the "Checking results" alert but I do not get the result[0] alert.
        As such I figured that the \\ in the \\. caused the problem.
        [color=blue]
        > But you can use RegExp literals instead which makes the Regular
        > Expression more legible since you need not to escape escape characters
        > of strings:
        >
        > var email_regex = /^(\w+)(@)(\w+)( \.)(\w+)$/;[/color]

        You know I wanted to use that too but evertime I did my JavaScript just
        blew up. Now it works! I think I forget the trailing ";" (I've been
        writing a lot of Tcl at work where semicolons are not used at the end of
        line).
        [color=blue]
        > BTW: In JavaScript, `@' need not to be escaped neither in string nor
        > in RegExp literals.[/color]

        I thought that but I was just backslashing it in case...

        OK I think it got it working now. Thanks.
        --
        Lottery: A tax on people who are bad at math.

        Comment

        • Dr John Stockton

          #5
          Re: RegExp to validate an email address

          JRS: In article <22e0d$3f9f6aa8 $44a7886c$23040 @msgid.meganews servers.co
          m>, seen in news:comp.lang. javascript, Andrew DeFaria
          <Andrew@DeFaria .com> posted at Tue, 28 Oct 2003 23:24:12 :-[color=blue]
          >
          > var email_address = "Joe@Schmoe ";
          > var email_regex = new RegExp ("^(\\w+)(\@)(\ \w+)(\.)(\\w+)$ ");
          > var result = email_regex.exe c (email_address) ;
          > alert (" result[1] = \"" + result[1] + "\"\n" +
          > " result[2] = \"" + result[2] + "\"\n" +
          > " result[3] = \"" + result[3] + "\"\n" +
          > " result[4] = \"" + result[4] + "\"\n" +
          > " result[5] = \"" + result[5] + "\"");
          >
          >The resulting alert box contains:
          >
          > result[1] = "Joe"
          > result[2] = "@"
          > result[3] = "Schm"
          > result[4] = "o"
          > result[5] = "e"
          >
          >It appears that the "\." is not escaping the "." to mean the literal
          >period. What am I doing wrong?[/color]

          (1) posting in HTML/multi-part.

          (2) having \ but not \\ before the dot.

          ISTM better to express RegExps as literals -
          RE = /^(\w+)(\@)(\w+) (\.)(\w+)$/

          I see no need to escape the @,
          nor to parenthesise the fixed parts @ and \. .

          --
          © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
          <URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
          <URL:http://www.merlyn.demo n.co.uk/js-index.htm> JS maths, dates, sources.
          <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.

          Comment

          • Thomas 'PointedEars' Lahn

            #6
            Re: RegExp to validate an email address

            Would you please configure your news client correctly as
            I asked and described at the bottom of my previous posting?

            Andrew DeFaria wrote:
            [color=blue]
            > Thomas 'PointedEars' Lahn wrote:[color=green]
            >> var email_regex = new RegExp ("^(\\w+)(@)(\\ w+)(\\.)(\\w+)$ "[/color]
            >
            > I had tried that. When I did the the following fails:
            >
            > var email_address = "Joe@Schmoe ";
            > var email_regex = new RegExp ("^(\\w+)@(\\w+ )(\\.)(\\w+)$") ;
            > var result = email_regex.exe c (email_address) ;
            > alert ("Checking results");[/color]
            52:[color=blue]
            > alert (" result[0] = \"" + result[0] + "\"");
            > alert (" result[1] = \"" + result[1] + "\"");
            > alert (" result[2] = \"" + result[2] + "\"");
            > alert (" result[3] = \"" + result[3] + "\"");
            > alert (" result[4] = \"" + result[4] + "\"");
            >
            > I get the "Checking results" alert but I do not get the result[0] alert.
            > As such I figured that the \\ in the \\. caused the problem.[/color]

            Yes, but different than you think. The above is the correct RegExp but it
            only matches strings that contain a dot. The value of `email_address' here
            ("Joe@Schmoe ") simply does not contain a dot, so there is no match and
            `result' therefore has no zero-property or no zeroth subexpression match
            (which would be equal to the string the whole RegExp matches):

            | Error: result has no properties
            | Source File: http://localhost/scripts/test/test2
            | Line: 52

            In contrast, "\." in the string which resulted in the subexpression /./,
            matches *any* character, namely the last `o' (since the second \w+ is
            greedy and the last \w+ matches `e'), so result[0] is "Joe@Schmoe " and
            not `undefined'.

            Try

            alert(new RegExp("^(\\w+) @(\\w+)(\\.)(\\ w+)$").exec("Jo e@Schmoe"));

            and

            alert(new RegExp("^(\\w+) @(\\w+)(\.)(\\w +)$").exec("Joe @Schmoe"));

            to find this confirmed.
            [color=blue][color=green]
            >> var email_regex = /^(\w+)(@)(\w+)( \.)(\w+)$/;[/color]
            >
            > You know I wanted to use that too but evertime I did my JavaScript just
            > blew up. Now it works! I think I forget the trailing ";" (I've been
            > writing a lot of Tcl at work where semicolons are not used at the end of
            > line).[/color]

            The trailing `;' is optional (though recommended) unless you have
            bad[tm] line-optimized code with two or more statements in a line.


            HTH

            PointedEars

            Comment

            • Andrew DeFaria

              #7
              Re: RegExp to validate an email address

              Thomas 'PointedEars' Lahn wrote:
              [color=blue]
              > Would you please configure your news client correctly as I asked and
              > described at the bottom of my previous posting?[/color]

              Ah.... No.

              --
              I used to work at a factory where they made hydrants; but you couldn't
              park anywhere near the place.

              Comment

              • Fabian

                #8
                Re: RegExp to validate an email address


                "Thomas 'PointedEars' Lahn" <PointedEars@we b.de> wrote in message
                news:3FA06928.5 010204@PointedE ars.de...[color=blue]
                > Would you please configure your news client correctly as I asked and[/color]
                described at the bottom of my previous posting?

                Would you please reconfigure yours as I asked *you*? Your line lengths
                are terrible!


                --
                --
                Fabian
                Visit my website often and for long periods!


                Comment

                • Thomas 'PointedEars' Lahn

                  #9
                  Re: RegExp to validate an email address

                  Fabian wrote:
                  [color=blue]
                  > "Thomas 'PointedEars' Lahn" <PointedEars@we b.de> wrote in message
                  > news:3FA06928.5 010204@PointedE ars.de...[color=green]
                  >> Would you please configure your news client correctly as I asked and[/color]
                  > described at the bottom of my previous posting?
                  >
                  > Would you please reconfigure yours as I asked *you*?[/color]

                  Message-ID, please!
                  [color=blue]
                  > Your line lengths are terrible![/color]

                  I don't know what's wrong with your news client (in fact I do know:
                  it's b0rken by default,) but mine is doing line-break automagically at
                  76 characters (except of URIs) as supposed, according to the standards:

                  ,--------------<http://www.rfc-editor.org/rfc/rfc2822.txt>---------------
                  | 2.3. Body
                  |
                  | The body of a message is simply lines of US-ASCII characters. The
                  | only two limitations on the body are as follows:
                  |
                  | [...]
                  |
                  | - Lines of characters in the body MUST be limited to 998 characters,
                  | and SHOULD be limited to 78 characters, excluding the CRLF.

                  If you don't believe me, let Google Groups be the referee:




                  HTH & HAND

                  PointedEars

                  Comment

                  • Lasse Reichstein Nielsen

                    #10
                    Re: RegExp to validate an email address

                    "Fabian" <lajzar@hotmail .com> writes:
                    [color=blue]
                    > "Thomas 'PointedEars' Lahn" <PointedEars@we b.de> wrote in message
                    > news:3FA06928.5 010204@PointedE ars.de...[color=green]
                    > > Would you please configure your news client correctly as I asked and[/color]
                    > described at the bottom of my previous posting?
                    >
                    > Would you please reconfigure yours as I asked *you*? Your line lengths
                    > are terrible![/color]

                    When I read the above two lines in the posting you reply to, none of
                    them is more than 72 characters. My newsreader doesn't wrap quotes
                    auotmatically, so I believe the problem is with your software.

                    In the message you replied to, there was only two lines (of
                    non-quotation) that were longer than 72 characters, and they were 73
                    and 74 respectively. Not something I would complain about.

                    /L
                    --
                    Lasse Reichstein Nielsen - lrn@hotpop.com
                    DHTML Demo: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                    'Faith without judgement merely degrades the spirit divine.'

                    Comment

                    • Dr John Stockton

                      #11
                      Re: RegExp to validate an email address

                      JRS: In article <wuanyprx.fsf@h otpop.com>, seen in
                      news:comp.lang. javascript, Lasse Reichstein Nielsen
                      <lrn@hotpop.com > posted at Thu, 30 Oct 2003 11:37:54 :-[color=blue]
                      >
                      >In the message you replied to, there was only two lines (of
                      >non-quotation) that were longer than 72 characters, and they were 73
                      >and 74 respectively. Not something I would complain about.[/color]

                      Agreed. Various RFCs and other sources suggest various margin
                      settings; for example FYI28 mentions 65 characters.

                      Given that there is a general expectation that most quoted lines
                      will not exceed 80 characters, and that some quoters use " >" as
                      indicator, ISTM that the right margin setting should not usually
                      exceed 72 characters for optimum results.

                      If the composing software permits quick altering of the margin
                      setting of a completed article, it may be worth trying a small
                      change when the text looks particularly ugly. I narrowed this
                      article a little, and the paragraphs are now almost justified.

                      --
                      © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                      <URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
                      <URL:http://www.merlyn.demo n.co.uk/js-index.htm> JS maths, dates, sources.
                      <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.

                      Comment

                      Working...