treehouse : what would you like to learn today?
Web Design Web Development iOS Development

jQuery Validation

  • Hi All,

    I am trying to write a validation script that will look at all the input's on the page and if the input is empty (value=""), pop up an alert that says which input it is. I feel that I am close, though when I hit submit the alert works but then the form submits anyways. Any help would be great.

    CodePen Link

      $("form").on("submit", function(){
        $("input").each(function(){
          var name = $(this).attr("name");
          if($(this).val() === ""){
            console.log("Please enter a" + " " + name);
            return false;
          }
        });
      });
    
  • If you are testing if a value is empty, null, etc you can simply modify that script, however, i suggest using the jQuery Validation plugin. Also, i once included this within a page (static page) along with the plugin but i dont believe you need it.

    $(function() {
       $('form').submit(function() {
          if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
             jQuery.data(this, "disabledOnSubmit", { submited: true });
             $('input[type=submit], input[type=button]', this).each(function() {
                $(this).attr("disabled", "disabled");
             });
             return true;
          } else {
             return false;
          }
       });
    });

    jQuery Validation Plugin Demo: http://jquery.bassistance.de/validate/demo/

  • Thanks for the quick response! I have used plugins in the past but I really wanted to try and write my own this time. I have messed around with some jQuery before though your script looks very confusing (No Offence), I have never seen jQery.data(......) or typeof before.

    Is my script written wrong?

  • Have a gander at this pen. This isn't very well written, however, you can definitely take and pull from this. I will attempt to comment it well.

    http://codepen.io/johnmotyljr/pen/JLrhK

  • Hi John,

    Thanks for the help, it worked!

    I have modified your code a little below and I'm just curious why you don't think this is well written code? I'm new to jQuery but would love to learn best practices.

    $("form").on("submit", function(e){
      $("input").each(function(){
    
        var name = $(this).attr("name");
    
        if($(this).val() == ""){
          console.log("There was an error" + " " + name);
          e.preventDefault();
        }else{
          return true; 
        }
      });
    });
    
  • @jcoder Are you new to Javascript as well or just jQuery?

    As far as this code, i felt it was a quick fix to a problem. Normally i would be more specific with my elements, test for every possible problem, and change the "input" for future use

    (<input type="submit || email || number || hidden || etc..."/>).

  • I'm fairly new to both, I have been using both for the past year but for very basic uses. I am trying to step up my game now!

    Thanks!

  • How does something like this look?

    $("form").on("submit", function(e){
      $("input").each(function(){
    
        var $this = $(this);
    
        if($($this).val() == ""){
    
          var name = $($this).attr("name");
          var li= $("<li></li>", {
            text: "There was an error with " + name,
            class: "errorText",
           });
    
          $($this).addClass("errorInput");
          $(".errorMessage").append(li);
          e.preventDefault();
        }else if($($this).val() != ""){
          $($this).removeClass("errorInput");
        }else{
          return true; 
        }
      });
    });
    
  • That looks good to my tired eyes, but for one thing you might want to consider -- any repeated error messages will continue to regenerate, until you've got a huge list on your hands, unless you somehow ensure that only error messages that are currently valid show.

    Let me take a look at a validation script I have on hand from an application I worked on awhile back . . .

  • Josh,

    Thanks for the comment, I definitely see what mean about the huge list every time it tries to validate. I made a quick update to prevent this. How does this look below?

    CodePen

    $("form").on("submit", function(e){
      $("li").remove();
    
      $("input").each(function(){
        var $this = $(this);
    
        if($($this).val() === ""){
          var formName = $($this).attr("name");
          var li       = $("<li></li>",{
            text: "There was an error with " + formName,
            class: "errorText",
          });
    
          $($this).addClass("errorInput");
          $(".errorMessage").append(li);
          e.preventDefault();
        } if($($this).val() != ""){
          $($this).removeClass("errorInput"); 
        } else{
          return true; 
        }
      }); //Input
    }); //Form .submit 
    
  • That looks much better!

  • Thanks!