views:

41

answers:

4

Hi,

I'm starting with jQuery and trying to save myself lots of code in a form validation. I thought to put all the form fields in an array, use each() to loop through the array to see if the fields are empty and return errors (if necessary).

One problem; my approach doesn't work..

I use the following method


     var fields = [ "$('#name')", "$('address')" ];
     jQuery.each(fields,function(){
      if(this.val() == ""){
       alert(this.id+" is empty");
       return false;
      }
     });

Of course i can check all fields separately, but because i have a lot of forms, that would be a pretty big code.

Are my thoughts even possible, and if they are, how?

Ok, the above problem is solved perfectly, but i now have a new one

Once i checked all the fields if they are empty, i want to check if a valid email is entered. I use the following code:


    $("#reservationForm").live("submit", function(f){
     $(".formError").hide();
     if(!$('#agree').is(':checked')){
      $("#agree").after('You need to agree with the terms on the right');
      f.preventDefault();
     }else{
      $("#reservationForm").find("input[type=email], input[type=tel], input[type=text]").filter(function(){
       if($(this).val() == ""){
        $(this).css("border","solid 1px red").after('Please fill in your '+this.id+'');
        $(this).find("first-child").focus();
        f.preventDefault();
       }else if(!/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b/.test($("#mail").val())){
        $("#mail").css("border","solid 1px red").after('Please enter a valid email address');
       }
      });
     }
    });

The problem is that the border doesn't turn red and the message that should be displayed after the e-mail field isn't displayed. Only the email field is focussed, nothing else.

Oh, and i actually have another 'problem' as well because the first-child selector doesn't seem to work. In stead of the first element, the last element is focussed. (I also tried last-child, but that didn't do the trick..)

+3  A: 

Remove the '"' in the array. You want to be storing the reference to the element, not a string ;-)

Also, take a look at:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

It's a great and simple-to-use jQuery form plugin! Oh, and you might want to change .val() to .attr("value") (although val might be valid, I'm not sure)

Oh, and if that still doesn't work try $(this) instead of just this, not 100% on the way jQuery handles this over $(this)

Alex
@Maurice - Be sure to accept answers on your questions if they resolve your issue :) The jQuery validation plugin is an excellent suggestion here :)
Nick Craver
@Nick - Of course i accept the answer, but see my reply below why i don't want to use that one :-) Thanks for the suggestion though!
Maurice
+1  A: 

How about finding if there are any empty elements in the form:

var emptyElements = $('#formId')
    .find(':text, :radio, :checkbox, select')
    .filter(function() { 
        var isEmpty = $(this).val() == '';
        if (isEmpty) {
            alert(this.id + ' is empty');
        }
        return isEmpty; 
    });
if (emptyElements.length > 0) {
    return false;
}

The jQuery validation plugin is also worth checking out.

Darin Dimitrov
That's a lot easier! Thanks!
Maurice
A: 
$.each($('form').serializeArray(), function(i, field) {
    if (field.value.length == 0 || field.value.match('regex of invalid syntax')) {
         // handle invalid data properly.
    }
})
thomasmalt
A: 

That works, thanks!!

I found that validation just a few minutes ago as well, thanks!

The reason that i don't want to use that one is that i want to learn jQuery myself. They say the best way to learn is practice, right? ;-)

I now have the following problem

I want to put appropriated errors underneath each fields. I tries the following, but that results in 'undefined'


     var fields = [ $('#name'), $('#address') ];
     jQuery.each(fields,function(){
      if(this.val() == ""){
       this.css("border","solid 1px red").after('Please fill in your '+$(this).id+'');
      }
     });

What am i doing wrong here?

Maurice
Don't "reply", that's not how this site works - this is a Q). If you need to change your question or reply to someone, you can either edit the question, or use the comment button.
Yi Jiang
Ok, sorry! Will remember that! :)
Maurice