Search code examples
javascriptjqueryformsvalidationclient-side-validation

Custom form validation with jQuery


Im using jQuery to make a custom form validation.

My issue is that when its alerting an error, i get every error in a separate alert dialog.. my goal is to have it list all errors in 1 single alert.

How do i achieve that?

This is my code:

jQuery(document).ready(function() {

  jQuery("form.kontakt-form").on("submit", function(e){
    jQuery(".kontakt-form input").each(function(){

      var name = jQuery(this).attr("placeholder");

      if(jQuery(this).val() == ""){
        alert("There was an error" + " " + name);
        e.preventDefault();
      }else{
        return true; 
      }
    });
  });

})

Solution

  • Use following

       jQuery(document).ready(function() {
        var nameErr = '';
          jQuery("form.kontakt-form").on("submit", function(e){
            jQuery(".kontakt-form input").each(function(){
    
              var name = jQuery(this).attr("placeholder");
    
              if(jQuery(this).val() == ""){
               nameErr += '\n'+name;
                e.preventDefault();
              }else{
                return true; 
              }
            });
            alert("There was an error" + " " + nameErr);
          });    
        })