简体   繁体   中英

validation for multiple forms generated by loop?

I have a for loop that generates 5 forms.There is lot of animation involved and only one form is displayed at a time.

My link

I have done the validation which is id based on some other page(working fine). But here the situation is different,I cannot generate id because of the loop.So my entire form validation is to be class based.

Myquestion: How do I manage a single function which validates all 5 forms.

If you are interested in my id based code-> this is thefiddle (not working),just the basic code

My code:for simplicity

for(i=0;i<=5;i++){
//html of my form in fiddle.
}

New to jquery.I do understand $(this) concept in jquery.

Hope I am clear.No plugin plz.

First things first, if an element is not unique do not use an ID for it.

Let's say we have 2 forms here:

<form id="formOne" class="validForm" method="post">
    <input class="email" type="text"/>
    <input class="newsletter" type="checkbox"/>
    <input type="submit" value="Send"/>
    <p class="error"></p>
</form>

<form id="formTwo" class="validForm" method="post">
    <input class="email" type="text"/>
    <input class="newsletter" type="checkbox"/>
    <input type="submit" value="Send"/>
    <p class="error"></p>
</form>

It's important to know your form elements are parents of your input or select elements. So when you use $(this) you can refer back to the parent.

To validate this in jQuery:

$('.validForm').submit(function(event){
    var allInputsAreValid = true;
    var form = null;
    $('.validForm input').each(function(){
        switch($(this).attr('class')){
            case 'email':
                if($(this).val() == "") {
                    allInputsAreValid = false;
                }
            break;
            case 'newsletter':
                // optional?
            break;
        }
        if(!allInputsAreValid) {
            form = $(this).parent();
            break;
        }
    });
    if(allInputsAreValid){
      // everything is valid, transfer data
    } else {
        event.preventDefault();
        $(form).children('.error').text(errorMessage);
    }
});

You mentioned you didn't want any plugins, which is fine. But I think you could learn a few things from going through the source code of an existing validation plugin like Parsley.js . I did, and I used what I learned to do a much simpler validation for my forms.

Basically it works by data-* tags to define what kind of input to expect from each field, then you can just loop through them like I assume you were already doing.

Example from the documentation:

<input type="text" id="email" name="email" data-trigger="change" data-required="true" data-type="email" />

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM