5

I am trying to get an email for my form to be validated like equalTo using the new Bootstrap 4. If possible i just want to use Bootstrap 4 and don't want to have to include any other library. I assume It just needs something in the javascript at the bottom that checks for matching fields. Any help is appreciated. I am surprised no one else has asked for this, or indeed an example is not on the Bootstrap website. I would imagine it to be a common requirement.

<!DOCTYPE html>
<html>

<head>
  <title>JQuery-validation demo | Bootstrap</title>
  <?php
echo '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">';
?>
</head>

<body>
  <form class="needs-validation" novalidate>
    <div class="form-row">
      <div class="col-md-4 mb-3">
        <label for="validationCustom01">Email</label>
        <input type="Email" class="form-control" id="email" placeholder="Email" required>
        <div class="valid-feedback">
          Looks good!
        </div>
      </div>
      <div class="col-md-4 mb-3">
        <label for="validationCustom02">Confirm Email</label>
        <input type="email" class="form-control" id="confirm_email" placeholder="Confirm Email" required>
        <div class="valid-feedback">
          Emails should match
        </div>
      </div>
    </div>

    <div class="form-group">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
        <label class="form-check-label" for="invalidCheck">
      Agree to terms and conditions
    </label>
        <div class="invalid-feedback">
          You must agree before submitting.
        </div>
      </div>
    </div>
    <button class="btn btn-primary" type="submit">Submit form</button>
  </form>

  <script>
    // Example starter JavaScript for disabling form submissions if there are invalid fields
    (function() {
      'use strict';
      window.addEventListener('load', function() {
        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.getElementsByClassName('needs-validation');

        // check match

        // Loop over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function(form) {
          form.addEventListener('submit', function(event) {
            if (form.checkValidity() === false) {
              event.preventDefault();
              event.stopPropagation();
            }
            form.classList.add('was-validated');
          }, false);
        });
      }, false);
    })();
  </script>
</body>

</html>
Chris
  • 95
  • 1
  • 1
  • 4
  • have you checked out the validation part in the Bootstrap docs under forms? Here is the link: https://getbootstrap.com/docs/4.0/components/forms/#validation – Corné Dec 14 '18 at 11:14
  • My issue is checking email = validation email. If not then display an error. I am trying to make sure people don't have typos in there emails. The Bootstrap email format check is fine. – Chris Dec 17 '18 at 13:50
  • Is this what you are looking for? https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript – Corné Dec 18 '18 at 08:00
  • The email validation is fine for an individual one. What i am really after is the something that will look at the first email and compare it against the other email. If they are not the same email address, halt the submission of the form. I would expect something inside the javascript that way like if (email.val <> confirm_email.val) then raise an error. – Chris Dec 18 '18 at 13:39
  • 1
    Oh, I understand what you are after now. I found this: https://stackoverflow.com/questions/30020681/compare-two-emails-in-two-text-fields-using-javascript It sounds like this is what you are after? – Corné Dec 18 '18 at 13:44
  • Thanks for your help. it's much appreciated. I have a working solutions below. :) – Chris Dec 19 '18 at 09:38
  • Cool, I am glad you are sorted. Just mark the answer that was applicable as "marked". – Corné Dec 19 '18 at 10:18

1 Answers1

2

try to use all the links properly... it will works

// Example starter JavaScript for disabling form submissions if there are invalid fields
    (function() {
      'use strict';
      window.addEventListener('load', function() {
        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.getElementsByClassName('needs-validation');

        // check match

        // Loop over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function(form) {
          form.addEventListener('submit', function(event) {
            if (form.checkValidity() === false) {
              event.preventDefault();
              event.stopPropagation();
            }
            var email = $("#email").val();
            var confirmemail = $("#confirm_email").val();
            if(email !== confirmemail){ 
            form.classList.add('was-validated');
              $("#validate").html("Email Should Match");
              $("#validate").addClass("error");
               $("#confirm_email").addClass("error-text");
              event.preventDefault();
              event.stopPropagation();              
            }
            else{
            $("#validate").removeClass("error");
            form.classList.add('was-validated');
               $("#confirm_email").removeClass("error-text");
              $("#validate").html("Looks Good!");
            }
           
          }, false);
        });
      }, false);
    })();
.error{
color:red !important;
}
.error-text{
border:1px solid red !important;
}
<!DOCTYPE html>
<html>

<head>
  <title>JQuery-validation demo | Bootstrap</title>
  <!--<?php
echo '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">';
?>-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>

<body>
  <form class="needs-validation" novalidate>
    <div class="form-row">
      <div class="col-md-4 mb-3">
        <label for="validationCustom01">Email</label>
        <input type="Email" class="form-control" id="email" placeholder="Email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required>
        <div class="valid-feedback">
          Looks good!
        </div>
      </div>
      <div class="col-md-4 mb-3">
        <label for="validationCustom02">Confirm Email</label>
        <input type="email" class="form-control" id="confirm_email" placeholder="Confirm Email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required>
       
        <div id="validate" class="valid-feedback">
          Emails should match
        </div>
      </div>
    </div>

    <div class="form-group">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
        <label class="form-check-label" for="invalidCheck">
      Agree to terms and conditions
    </label>
        <div class="invalid-feedback">
          You must agree before submitting.
        </div>
      </div>
    </div>
    <button class="btn btn-primary" type="submit">Submit form</button>
  </form>
</body>

</html>
Udhay Titus
  • 5,761
  • 4
  • 23
  • 41
  • I am trying to check if email = validation email. If not display and error. – Chris Dec 17 '18 at 13:51
  • 1
    @Chris in your input try to add `pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"` it will works otherwise you have to add regular expression in your jquery it will help. I updated the answer check it now. – Udhay Titus Dec 18 '18 at 04:30
  • The email validation is fine for an individual one. What i am really after is the something that will look at the first email and compare it against the other email. If they are not the same email address, halt the submission of the form. I would expect something inside the javascript that way like if (email.val <> confirm_email.val) then raise an error. – Chris Dec 18 '18 at 13:38
  • Thats what i was after. Works just like i wanted. Thanks for your help. Hope other people will use this too as i can't be the only one who needs this :) – Chris Dec 19 '18 at 09:37
  • Just a quick follow up: i want to display a message if the emails don't match. New to Bootstrap 4 and jQuery so stumbling in the dark to be honest. var $conf = $("#confirm_email"); if(email !== confirmemail){ event.preventDefault(); event.stopPropagation(); $conf.setCustomValidity("The emails dont match"); $conf.invalid; } – Chris Dec 21 '18 at 09:20
  • I have the
    Please enter a valid email address
    default error. But i also want it to say if the emails don't match as well. It should display the error messages and mark the box as red. Ps. thanks for you help. This is a piece of work for an Orphans charity (not joking).
    – Chris Dec 21 '18 at 10:18
  • This code works but on submit button click. Is it possible to validate email, on the go as we type? – Khaja Moinuddin Jul 19 '20 at 11:44
  • @KhajaMoinuddin yes we can do by using `$("button").click(function(){ //do your validation here });` – Udhay Titus Jul 21 '20 at 06:06