1

I am trying to make a form with Materialize that validates one email. I start off with a submit button toggled to disabled. Ideally, when the email is filled in and validated, the submit button will stop being disabled and the user can click it to the next page. Here is my HTML:

<form id="survey">

        <div class="input-group">
            <p class="input-header">Enter Your Email</p>
            <div class="input-block input-field">
        <input id="email" type="text" name= "email" class="validate" required="" aria-required="true">
        <label for="email">Email Address</label>
      </div>
      <br></br>

        <a class="waves-light btn red lighten-2 disabled" id="submit">Submit
        <i class="material-icons right">send</i>
        </a>
        <br></br>
        <br></br>
        <br></br>

</form>

Here is the JavaScript/jQuery:

$(document).ready(function(){
  $('.parallax').parallax();

$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
  $.post('insert.php', $('#survey').serialize());
 window.location.href = 'thankyou.php';
}
});

$('body').on('click', 'input', function() {
checkValidity($(this));
});
$('body').on('focusout', 'input', function() {
checkValidity($(this));
});

function checkValidity (current) {
let isValid = true;
if (!current.val()) {
  isValid = false;
} else {
  isValid = iteratatingForm(current);
}
const submit = $('#submit');
if (isValid) {
  submit.removeClass('disabled');
} else {
  if (!submit.hasClass('disabled')) {
    submit.addClass('disabled');
  }
}
}

function iteratatingForm (current) {
if (!document.forms['survey']['email'].value) return false;
return true;
}});

Please let me know what I'm doing wrong! Thanks!

Yikes
  • 87
  • 1
  • 11

2 Answers2

2

You can use email type for your input and a button submit who will trigger validation input. I added a function to check if email is valid with a regex. (Found here : How to validate email address in JavaScript? ) You have to add jQuery Validation Plugin

$(document).ready(function(){
  
  $('#survey input').on('keyup', function(){
   var validator = $("#survey").validate();
  if (validator.form() && validateEmail($('#email').val())) {
    $('#submitButton').prop('disabled', false);
    $('#submitButton').removeClass('disabled');
  }
    else{
      $('#submitButton').prop('disabled', true);
      $('#submitButton').addClass('disabled');
      }
  }  );

  function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\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,}))$/;
    return re.test(email.toLowerCase());
}
  /*
    Confirmation Window
  */
  $('body').on('click', '#submit', function() {
    let decision = confirm('Are you sure you would like to submit your survey?');
    if (decision) {
      $.post('insert.php', $('#survey').serialize());
     window.location.href = 'thankyou.php';
    }
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet"/>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<form id="survey">

   <div class="input-group">
    <p class="input-header">Enter Your Email</p>
    <div class="input-block input-field">
         <input id="email" type="email" name= "email" class="validate" required="true" aria-required="true">
         <label for="email">Email Address</label>
       </div>

  <button type="submit" form="survey" value="Submit" class="waves-light btn red lighten-2 disabled" disabled='disabled' id="submitButton">Submit</button>
  </form>

StackOverflow snippet bug due to jQuery validation plugin, but it works in CodePen

Toodoo
  • 8,570
  • 6
  • 35
  • 58
0

Another way to solve this is to add a regex field to your <input ... elements e.g.

<div class="input-field col s6">
  <input id="email" type="text" class="validate" value="hello@email.com" regex="(?!.*\.\.)(^[^\.][^@\s]+@[^@\s]+\.[^@\s\.]+$)" required="" aria-required="true" value="hello@email.com" >
  <label for="email">Email</label>
  <span class="helper-text" data-error="Invalid email address."></span>
</div>

The nice thing about this is you can have individual regex validation for other fields. For example, you could have other inputs such as name / age e.g.

  1. name (only contain groups of UPPER-CASE characters separated by a single space e.g. JAMES JONES - regex = ^[A-Z]*(\s[A-Z]+)*$).
  2. age (only contain numbers - regex = ^\d+$).

NOTE: - I recommend the https://regex101.com/ website to test our your regex expressions against example text.

To validate using e.g. JQuery - you would add listeners to each of your input elements: -


$(document).ready(function(){
  $("input").on('input propertychange blur', function(event) {
    var elm = event.currentTarget;
    var val = elm.value;
    var isValid = true; // assume valid
    
    // check if required field
    if (elm.hasAttribute("required")) {
      isValid = val.trim() !== '';
    }
    // now check if regex
    if (isValid && elm.hasAttribute("regex")) {
      var regex = new RegExp(elm.getAttribute("regex"), 'g');
      isValid = regex.test(val);
    }
    
    elm.classList.remove(isValid ? "invalid" : "valid");
    elm.classList.add(isValid ? "valid" : "invalid");
    updateButtonState();
  });
});

function updateButtonState () {
  var numOfInvalid = $('input.invalid').length;
  if (numOfInvalid > 0) {
    $('.submit-button').prop('disabled', true);
    $('.submit-button').addClass('disabled');
  }
  else{
    $('.submit-button').prop('disabled', false);
    $('.submit-button').removeClass('disabled');
  }
}

When the page loads the JQuery function listens to changes to the input (and also blur events). It first of all checks if the input is a required field and validates that first. Next of all, it checks if a regex attribute exists, and if so, performs regular expression based validation.

If the validation fails, then the function adds/removes classes related to Materialize CSS and then finally updates the button state. This is optional but very nice if you are filling in a form (button is only enabled if everything is valid).

See the following CodePen to see everything in action: -

regex validation in action

bobmarksie
  • 3,282
  • 1
  • 41
  • 54