1

The script below is suppose to insert a message using .insertAfter() if a user doesn't type in an @ symbol within a field . This script also displays an error message if the user types in a value that matches a value from the invalidEmailAddresses array.

For some reason only the second part of this script executes. If a user types in an @ symbol they get a message but if the user types in an address similar to test@yahoo.com a message doesn't display. Not sure if i organized the code correctly.

$(document).ready(function(){

    $("input[name='emailAddress']").blur(function(){
        // Actual Email Validation function

            var hasError = false;
            var emailaddressVal = $("input[name='emailAddress']").val();
            var invalidEmailAddresses = 
            ['goddady.com', 'aol.com', 'yahoo.com', 'yahoo.fr'];     


            if ($.inArray(emailaddressVal,invalidEmailAddresses) > 0) {
                $( "<span id='emailMessage'>The email provided is not from a business related domain. Please use an appropriate email address instead.</span>" ).insertAfter( "input[name='emailAddress']" );
            } else {
                    $ ('#emailMessage').css('display','none');
                }

            if ($("input[name='emailAddress']").val().indexOf('@') > -1) { 
                   $ ('#emailMessage').css('display','none');     
        } 

        else {
                $( "<span id='emailMessage'>The email provided does not contain an @ symbol</span>" ).insertAfter( "input[name='emailAddress']" );
        } 
            if(hasError == true) { return false; }
    });

});
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Spanky
  • 699
  • 2
  • 11
  • 38
  • What do you want your code to do? Tell me exactly what is your requirement. – Sukanya1991 Apr 01 '15 at 19:46
  • I would like to display an error message if the user types in a value that matches a value from the invalidEmailAddresses array. And display an error message if the user doesn't type in an @ symbol. – Spanky Apr 01 '15 at 20:01
  • 1
    what i understand is that if the user types jimmy@yahoo.com or jimmy@aol.com then he should get an error message. Right? – Sukanya1991 Apr 01 '15 at 20:04
  • @Sukanya Correct! Or if you are missing an "@" symbol you should get an error as well – Spanky Apr 01 '15 at 20:24
  • 1
    I have refactored your code in my answer, should work now :) – Terry Apr 01 '15 at 20:45

2 Answers2

2

The issue lies with this if conditional: if ($.inArray(emailaddressVal,invalidEmailAddresses) > 0).

Since the $.inArray() method returns the index of a string found, when a value of 0 is returned, it is actually found—but at the start of the string (position 0, because JS is zero-based). So, you should use !== -1 instead, i.e.: if ($.inArray(emailaddressVal,invalidEmailAddresses) !== -1).

However, this does not completely solve your issue$.inArray() only compares string, it does not search for it. Therefore if your string contains the blacklisted email domains, but does not match exactly, it will return false. In this case, you should use regular expression instead. The strategy is simple: use .each() to loop through your array, and take the value, use it to construct an expression which we will test your email address that is provided against.

Also, since there is the possibility that the user-entered email address fails both tests, two <div> of identical IDs will appear. This is invalid HTML. Instead, try using a class instead.

p/s: I also recommend changing listening to .blur() to .change() instead. It is more robust :)


With all the points above considered, I have refactored your code a little:

  • Declare a global (but still within function scope) error array called hasError. It will be used to store all error messages you get, since we cannot be sure if there will be one, or more than one error.
  • We construct two tests:
    1. To test if email matches against blacklist using the string.search(regexp) method. If there is a match, the value returned will exceed -1. We then push the relevant error message into hasError in an object
    2. To test if email contains the @ sign, we use your default logic (which works beautifully). If there is an error, we push, again, the relevant error message into hasError in an object
  • At the end, we evaluate hasError. If it is not empty, then we know there is an error somewhere, and loop through it. The error messages are accessible via the messages keyword :)

Without further ado, here's your code:

$(document).ready(function() {

  $("input[name='emailAddress']").change(function() {

    // Actual Email Validation function
    var hasError = [],
        emailaddressVal = $("input[name='emailAddress']").val(),
        invalidEmailAddresses = ['godaddy.com', 'aol.com', 'yahoo.com', 'yahoo.fr'];

    // Check against blacklist
    $.each(invalidEmailAddresses, function(i, v) {
      var pattern = new RegExp(v, 'i');
      if (emailaddressVal.search(pattern) > -1) {
        hasError.push({
          'test': 'blacklist',
          'message': 'The email provided is not from a business related domain. Please use an appropriate email address instead.'
        });
      }
    });

    // Check if there is an '@' character
    if ($("input[name='emailAddress']").val().indexOf('@') === -1) {
      hasError.push({
        'test': '@ sign',
        'message': 'The email provided does not contain an @ symbol'
      });
    }

    console.log(hasError);
    // Error handling
    $('#error').remove();
    if(hasError.length > 0) {
      var $error = $('<div id="error"><ul></ul></div>');
      $.each(hasError, function(i,v) {
        $error.find('ul').append('<li>'+v.message+'</li>');
      });
      $error.insertAfter("input[name='emailAddress']");
    }

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input name="emailAddress" type="email" />
</form>
Community
  • 1
  • 1
Terry
  • 63,248
  • 15
  • 96
  • 118
2

This is working if you add the following code

    $(document).ready(function() {

  $("input[name='emailAddress']").blur(function() {
    // Actual Email Validation function
    $('#emailMessage').html("");
    var hasError = false;
    var emailaddressVal = $("input[name='emailAddress']").val().trim();
    var invalidEmailAddresses = ['goddady.com', 'aol.com', 'yahoo.com', 'yahoo.fr'];

    if (!isValidEmailAddres(emailaddressVal)) {
      $("<span id='emailMessage'>The email provided does not contain an @ symbol</span>").insertAfter("input[name='emailAddress']");
      hasError = true;
    } else {
      debugger
      emailaddressVal = emailaddressVal.split('@').slice(1)[0].trim();

      if ($.inArray(emailaddressVal, invalidEmailAddresses) >= 0) {
        $("<span id='emailMessage'>The email provided is not from a business related domain. Please use an appropriate email address instead.</span>").insertAfter("input[name='emailAddress']");
      } else {
        $('#emailMessage').css('display', 'none');
      }
    }
    if (hasError == true) {
      return false;
    }
  });

  function isValidEmailAddres(emailID) {
    var regexExp = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return regexExp.test(emailID);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="emailAddress" />
Sukanya1991
  • 778
  • 3
  • 17