0

Fairly new to jquery but I realize my code could be condensed. It works just fine but there's got to be a better way to do this as it kind of seems like redundant code. I've got two input fields and a textarea that I'm validating see below. Code samples would be ideal since I'm still learning but any help is appreiacted:

$("form#designForm").submit(function(){

    if($("#ccDesignFirstName").val().length == 0){
      alert("Full Name field is required");
      $("#ccDesignFirstName").focus();
      return false;
    }        

    if($(".telephoneInput").is(":visible")){
        if($("#ccDesignTelephone").val().length == 0){
          alert("Phone is required");
          $("#ccDesignTelephone").focus();
          return false;
        }
    }

    if($("#ccDesignProblem").val().length == 0){
      alert("Question is required");
      $("#ccDesignProblem").focus();
      return false;
    }
});
4

2 回答 2

1

To iterate through all the inputs in a form you can do this:

$("form#designForm").submit(function(){
    var valid = true;
    $("form#designForm :input").each(function(){
        //$(this) is the jquery object of the input.
        //do your validation here
        if($(this).val().length == 0){
            valid = false;
        }
        //some more validation if needed...
    });
    return valid;
});

This uses the jquery [:input selector][1] to get ALL types of inputs, if you just want text you can do :

$("form#designForm input[type=text]")

etc.

于 2013-05-09T22:47:50.507 回答
0

Yeah, there are a few different strategies for form validation you can do. My personal favorite is to add classes to the elements you want to validate.

Need all fields to not be left blank? Add check-empty class to the inputs. Need to check for email validation? Add an email class. In your JavaScript you can then use a single jQuery selector and go over each input by category and ensure that each check passes.

I went a little overboard here and used .apply() for each function. In all honesty this technique will not hold up if you need to do something asynchronous (AJAX request to the server to ensure the email is unique, for example).

If you need to check with AJAX, you would need to use callbacks to ensure everything validated. Generally speaking, something like that happens once or twice, so there's no need to get too fancy with it. If you do have a form that is very AJAX-call heavy, you may consider using jQuery's $.Deferred.

Let me know if you have any questions. This is just my personal take on form validation, I'm there are very many more ways of doing it as well. I find validating via CSS rules allows you to check fields in other areas as well. And this is pretty reusable; form validation is a common task on the web. Once you have a solid solution, it's just a matter of applying it to your particular situation.

于 2013-05-10T01:14:33.167 回答