9

Form Validation Check Fields

 2 years ago
source link: https://www.codesd.com/item/form-validation-check-fields.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Form Validation Check Fields

advertisements

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..)


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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK