Validate separate forms with one function - this input

Hi all

I have a jsfiddle here - http://jsfiddle.net/Lxvzuznt/13/

It’s a simple single form with jquery validation.

I need to have more than one form on the page.

The forms are created dynamically so I’d like the id’s of the input fields to be the same.

The different forms will sign up users to different events so they will capture the same information but for different use.

Is there a way to use one validation function and say validate the input related to ‘this’ button

$(function(){
    $('.btn').click(function(e){
        e.preventDefault();
        if(valFields()){
    
        }
    })
})

function valFields(){

    var flag = true;

    var name = $(this).parent().$('#name');
    var number = $(this).parent().$('#number');

    if(name.val().length == 0){
        alert('No Name');
    }

    if(number.val().length == 0){
        alert('No Number');
    }

    return flag;
}

Hi duckhill,

Element IDs have to be unique within the document, you can’t reuse the same ID attribute for different fields. This shouldn’t be a problem for dynamically created forms - just append a number to the end of the ID. What you should do is give each input a ‘name’ attribute. This can be reused across separate forms and means that your data will be named consistently when received server-side.

Here’s one solution to your question:

function valFields(fields){ 
    var isValid = true;
    
    if(fields.name.length == 0){
        isValid = false;
    }
    
    if(fields.number.length == 0){
        isValid = false;
    }
    
    return isValid;
}

$('.forms').on('submit', 'form', function(e){
    e.preventDefault();

    var formData = {};

    $.each( $(this).serializeArray(), function(index, value) {
        formData[value.name] = value.value;
    });
    
    if( valFields( formData ) ){
        console.log('validation passed');
    } else {
        console.log('validation failed');   
    }
});

There are a couple of things to note:

  • The submit handler is attached to a container element - this means that it will fire for dynamically added forms automatically.
  • I’m using jQuery’s serializeArray method to get an array of the form input values, and looping over this to create a simple data object to pass to the valFields function - the reason for doing this is to avoid valFields having to know anything about the form. You could re-use the function to validate the data no matter where it comes from.