Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

jquery validate submithandler


function submithandler() {
	var errors = [];
	formFields.forEach( (field) => {
    	
        // loop to check all rules attached to the fields
        field.rules.forEach( (rule) => {
        
        	if (rule == 'required' && ! $(`#${field.id}`).val().length) {
            	errors.push(`${field.id} is required!`)
            } else if (rule.includes('max:')) {
            	let limit = rule.split(':')[1]; // this will get the number attached to the max rule
                if (limit > $(`#${field.id}`).val().length ) {
                	errors.push(`maximum length of charater must be `${limit})
                }
            }
        
        })
        
    })
    
    if (errors.length) {
      
     	return errors;
    }
  
  //do ajax post here
  
  
  
}


// edit the code below base on what u need

var formFields = [
	{
    	id:'name', // use to access the dom.eg $('#name')
        rules:['required']
    },
    {
    	id:'phone',
        rules:['required', 'max:11'],
    }
];
 
PREVIOUS NEXT
Tagged: #jquery #validate #submithandler
ADD COMMENT
Topic
Name
4+5 =