Search code examples
jqueryregexemail-validation

jquery validating email not working with ^ character


I'm trying to validate an email following the explanations on this page Email validation using jQuery, but I don't know why I get an error if I put this character ^ at the beginning of my expression:

function checkEmail(){
    var email = this.innerHTML;
    var emailPattern = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z]{2,4})+$/;

    if (!emailPattern.test(email)){
        alert("Invalid email address.");
    }
    else {
        alert("Valid email address.");
    }
}

If I use the other one (without ^ and +$) it works perfectly:

var emailPattern = /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/;

Just to understand it, What is wrong with my first expression?

Here is a fiddle that demonstrate my problem: http://jsfiddle.net/5en4cxy9/

Thanks,


Solution

  • Your fiddle includes a leading space before the email address. This leading space is included in .text() or .innerHTML, so the anchored regex (/^.../) fails.

    Trim leading/trailing spaces first:

    var email = this.innerHTML.trim();
    var emailPattern = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z]{2,4})+$/;
    
    if (!emailPattern.test(email)){
        alert("Invalid email address.");
    }
    else {
        alert("Valid email address.");
    }
    

    $(document).ready(function() {
      $("div").blur(function() {
        // alert("This input field has lost its focus.");
        var email = $("div#email").text().trim();
    
        var emailPattern = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z]{2,4})+$/;
    
        if (!emailPattern.test(email)) {
          alert("Invalid email address.");
          $(this).css('color', 'red');
        } else {
          alert("Valid email address.");
        }
    
    
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <table id="myTable">
      <tbody>
        <tr class="tabel_header">
          <th width="10%" align="center"><strong> Email:</strong>
          </th>
          <th width="7%" align="center"><strong> Username:</strong>
          </th>
        </tr>
        <tr data-row-no="1" height="35">
          <td>
            <div id="email" style="width: 100%; height: 100%;" contenteditable="true"> [email protected]</div>
          </td>
          <td>
            <div style="width: 100%; height: 100%;" contenteditable="true">Admin</div>
          </td>
        </tr>
      </tbody>
    </table>