Search code examples
jqueryformscustomvalidator

Jquery validator form


I am currently doing a small form with jquery, the grace of this form is that when an error of that type is missed, I send it in the html and put it in a small div that has each input below, according to the type of error that jump, now I have the problem of duplicates and that the error that corresponds is not added

$('form.registerForm').submit(function() {
    var f = $(this).find('.form-group'),
      ferror = false,
      emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;
      var p1 = $('#password1').val();
      var p2 = $('#password2').val();
      

      f.children('input').each(function() { // run all inputs
      var i = $(this); // current input
      var rule = i.attr('data-rule');
      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {

          case 'password':
            if ( p1 != p2 ) {
              ferror = ierror = true;
              
              f.find('.validation').text("Errno password");
              
            }
          break;

          case 'name':
            if ( !isNaN(i.val()) ) {
              ferror = ierror = true;
              alert(f);
              f.find('.validation').text("Errno no numbers");     
            }
            break;


          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
              f.find('.validation').text("Errno needed");
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
              f.find('.validation').text("Errno long");
            }
            break;

          case 'email':
            if (!emailExp.test(i.val())) {
              ferror = ierror = true;
              f.find('.validation').text("Errno email ");
            }
            break;

          case 'checked':
            if (!i.attr('checked')) {
              ferror = ierror = true;
              f.find('.validation').text("Errno checker");
            }
            break;


          case 'regexp':
            exp = new RegExp(exp);
            if (!exp.test(i.val())) {
              ferror = ierror = true;
              f.find('.validation').text("Errno regexp");

              
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'Passwords repetidas') : '')).show('blind');
      }

    });

    if (ferror) return false;
    else var str = $(this).serialize();
    $.ajax({
      type: "POST",
      url: "contactform/contactform.php",
      data: str,
      success: function(msg) {
        // alert(msg);
        if (msg == 'OK') {
          $("#sendmessage").addClass("show");
          $("#errormessage").removeClass("show");
          $('.contactForm').find("input, text").val("");
        } else {
          $("#sendmessage").removeClass("show");
          $("#errormessage").addClass("show");
          $('#errormessage').html(msg);
        }

      }
    });
    return false;
  });

});
<form action="" method="post" role="form" class="registerForm">
    <div id="sendmessage">You did the register!</div>
    <div id="errormessage"></div>
    <ul class="contact-list">
        <li class="form-group">
            <label><i class="icon-envelope-alt"></i> Email </label> 
            <input type="email" class="form_input" name="email" id="email" placeholder="Email" data-rule="email" data-msg="" />
            <div class="validation"></div>
        </li>
        <li class="form-group">
            <label><i class="icon-edit"></i> Password </label>
            <input type="password" class="form_input" name="password" id="password1" placeholder="Contraseña" data-rule="password" data-msg="" />
            <div class="validation"></div>
        </li>
        <li class="form-group">
            <label><i class="icon-edit"></i> Repeat password</label>
            <input type="password" class="form_input" name="password" id="password2" placeholder="Repite la contraseña" data-rule="password" data-msg="" />
            <div class="validation"></div>
        </li>
        <li class="form-group">
            <label><i class="icon-pencil"></i> Name </label> 
            <input type="text" class="form_input" name="name" id="name" placeholder="Introduce tu nombre" data-rule="name" data-msg="" />
            <div class="validation"></div>
        </li>
        <li class="form-group">
            <label><i class="icon-pencil"></i> Surname </label> 
            <input type="text" class="form_input" name="surname" id="surname" placeholder="Introduce tus apellidos" data-rule="name" data-msg="" />
            <div class="validation"></div>
            </li>
        <li class="last">
            <button class="btn btn-large btn-theme" type="submit" id="send">Register</button>
        </li>
    </ul>
</form>

My fiddle: https://jsfiddle.net/ho8crseu/


Solution

  • Based on your validation logic, you need to update the data-msg value for each input when detected an error, instead of update the html text of the $('.validation') div directly.

    jQuery(document).ready(function($) {
      "use strict";
    
      //Contact
      $('form.registerForm').submit(function() {
        var f = $(this).find('.form-group'),
          ferror = false,
          emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;
          var p1 = $('#password1').val();
          var p2 = $('#password2').val();
          
    
          f.children('input').each(function() { // run all inputs
          var i = $(this); // current input
          var rule = i.attr('data-rule');
          if (rule !== undefined) {
            var ierror = false; // error flag for current input
            var pos = rule.indexOf(':', 0);
            if (pos >= 0) {
              var exp = rule.substr(pos + 1, rule.length);
              rule = rule.substr(0, pos);
            } else {
              rule = rule.substr(pos + 1, rule.length);
            }
    
            switch (rule) {
    
              case 'password':
                if ( !p1 || !p2 || p1 != p2 ) {
                  ferror = ierror = true;
                  i.attr("data-msg", "Errno password");
                  
                }
              break;
    
              case 'name':
                if ( !isNaN(i.val()) ) {
                  ferror = ierror = true;
                  //alert(f);
                  i.attr("data-msg", "Errno no numbers");     
                }
                break;
    
              case 'required':
                if (i.val() === '') {
                  ferror = ierror = true;
                  i.attr("data-msg", "Errno needed");
                }
                break;
    
              case 'minlen':
                if (i.val().length < parseInt(exp)) {
                  ferror = ierror = true;
                  i.attr("data-msg", "Errno long");
                }
                break;
    
              case 'email':
                if (!emailExp.test(i.val())) {
                  ferror = ierror = true;
                  i.attr("data-msg", "Errno email ");
                }
                break;
    
              case 'checked':
                if (!i.attr('checked')) {
                  ferror = ierror = true;
                  i.attr("data-msg", "Errno checker");
                }
                break;
    
    
              case 'regexp':
                exp = new RegExp(exp);
                if (!exp.test(i.val())) {
                  ferror = ierror = true;
                  i.attr("data-msg", "Errno regexp");
                }
                break;
            }
            i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'Passwords repetidas') : '')).show('blind');
          }
    
        });
    
        if (ferror) return false;
        else var str = $(this).serialize();
        $.ajax({
          type: "POST",
          url: "contactform/contactform.php",
          data: str,
          success: function(msg) {
            // alert(msg);
            if (msg == 'OK') {
              $("#sendmessage").addClass("show");
              $("#errormessage").removeClass("show");
              $('.contactForm').find("input, text").val("");
            } else {
              $("#sendmessage").removeClass("show");
              $("#errormessage").addClass("show");
              $('#errormessage').html(msg);
            }
    
          }
        });
        return false;
      });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <!-- start contact form -->
    <form action="" method="post" role="form" class="registerForm">
      <div id="sendmessage">You did the register!</div>
      <div id="errormessage"></div>
      <ul class="contact-list">
        <li class="form-group">
          <label><i class="icon-envelope-alt"></i> Email </label> 
          <input type="email" class="form_input" name="email" id="email" placeholder="Email" data-rule="email" data-msg="" />
          <div class="validation"></div>
        </li>
        <li class="form-group">
          <label><i class="icon-edit"></i> Password </label>
          <input type="password" class="form_input" name="password" id="password1" placeholder="Contraseña" data-rule="password" data-msg="" />
          <div class="validation"></div>
        </li>
        <li class="form-group">
          <label><i class="icon-edit"></i> Repeat password</label>
          <input type="password" class="form_input" name="password" id="password2" placeholder="Repite la contraseña" data-rule="password" data-msg="" />
          <div class="validation"></div>
        </li>
        <li class="form-group">
          <label><i class="icon-pencil"></i> Name </label> 
          <input type="text" class="form_input" name="name" id="name" placeholder="Introduce tu nombre" data-rule="name" data-msg="" />
          <div class="validation"></div>
        </li>
        <li class="form-group">
          <label><i class="icon-pencil"></i> Surname </label> 
          <input type="text" class="form_input" name="surname" id="surname" placeholder="Introduce tus apellidos" data-rule="name" data-msg="" />
          <div class="validation"></div>
        </li>
        <li class="last">
          <button class="btn btn-large btn-theme" type="submit" id="send">Register</button>
        </li>
      </ul>
    </form>
    
    <!-- end contact form -->