jQuery to match an input field value against a pre-defined value on focusout

Here is how to show a message on a form when the input field loses focus and it matches a predefined value. In this example a message appears if the user enters an email address that matches the domain of a free email provider, eg. Hotmail, Yahoo & Gmail.

NOTE: this doesn't validate and stop the user from being able to submit the form, it's just a message that appears. If you use the Webform module and want to prevent a user from submitting a form you can do this by also enabling the Webform Validation module and adding a Form Validation Rule of the type Words Blacklist.

Anyway back to creating a jQuery message which appears when a form input value matches a predefined value...

The below script checks for a match when the field loses focus - in this instance it's checking for '@hotmail.', '@yahoo.' & '@gmail.'. It was done in this way so that it matches for both '@yahoo.com' and '@yahoo.co.uk', and isn't case sensitive. You can build quite complex rules for matching using JavaScript regular expressions (RegEx).

The message is inserted directly after the email input field, and is removed once the match isn't found anymore.

<form>
    <input class="form-email" type="email" id="edit-submitted-email-address" name="submitted[email_address]" size="60">
</form>

<script>
(function ($) {     
    $('input.form-email').focusout(function(){
        var match = $(this).val().match(/@hotmail\.|@yahoo\.|@gmail\./gi);
        if(match){
                $(this).not('.emailAlertActive').after( '<p class="emailAlert">Please use your business email address.</p>' ).addClass('emailAlertActive');
        } else {
            $(this).siblings('.emailAlert').remove();
            $(this).removeClass('emailAlertActive')
        }
    })})(jQuery);
</script>
Justin Chevallier

Justin Chevallier

Avid Drupal site builder & user for +9 years.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.