Form validation and form submit

  • Notes
    1. script
    
                    
      //used in form blades
      $(document).on('click','#btn_save, .btn_save',function(event) {   
        
           
           // var formId= $(this).attr('data-form');
            var formId=  $(this).closest('form').attr('id');
            //var formId=$(this).parent().closest('form');
           
            var ajax_url= $(this).attr('data-ajax_url');
            var beforeAction= $(this).attr('data-beforeAction');
            var afterAction= $(this).attr('data-afterAction');
            var callBackFunction=$(this).attr('data-callBackFunction');
           
          
            
            formValidation(formId, beforeAction, afterAction, ajax_url, callBackFunction); 
    
      });
    
    
     $("#btn_draft").click(function() {
        var formId=  $(this).closest('form').attr('id');
        var ajax_url= $(this).attr('data-ajax_url');
        var beforeAction= $(this).attr('data-beforeAction');
        var afterAction= $(this).attr('data-afterAction');
    
         $('#mode').val('draft');
         $('.form-control').removeClass('mandatory');
        formValidation(formId, beforeAction, afterAction ,ajax_url); 
    });
    
      var isPostRequest=0;   
      function formValidation(formId, beforeAction='', afterAction='', ajax_url='', callBackFunction=''){
                 var error=0;
                 var focusStatus=0;
                
               
                 if(beforeAction==1){
                   // error=doBeforeAction(error);  
                   error=eval(doBeforeAction+"(error)");            
                 }
    
    
                $('#'+formId+' .mandatory').each(function(index, obj){
                // $('.'+formId).children('.mandatory').each(function(index, obj){
                    
                    switch(obj.type){
                       case 'radio':
                            var length=$("input[name="+obj.name+"]:checked").length;
                            if(length==0){
                                $(obj).parent().next('.errormessage').show();			
                                $(obj).parent().next('.errormessage').text($(obj).data('message')); 
                                error=1;      
                            }
                       break;
                      
    
                       default:
                            if(obj.value==''){
     
                                console.log($(obj).data('message'));
                                $(obj).parent().find('.errormessage').show();			
                                $(obj).parent().find('.errormessage').text($(obj).data('message')); 
                                if(focusStatus==0){
                                    $(obj).focus();
                                    focusStatus=1;
                                }
                                
                                error=1;      
                              //return false;              
                              
                            }
                       break;
                    }                 
                   
                    
                });
    
                //multiselect
                $('#'+formId+' .filter-multi-select').each(function(index, obj){           
                    multiItems=$(obj).find('.selected-items .item').length
                    if(multiItems==0){
                        $(obj).parent().find('.errormessage').show();	
                        $(obj).parent().find('.errormessage').text('Please select items'); 
                    }
                });
    
    
                if(afterAction==1){
                   //error=doAfterAction(error);  
                   error=eval(doAfterAction+"(error)");            
                }
    
             
    
                if(error==0){
                    $('#overlay1').fadeIn();
                    $('#btn_save').prop('disabled', true);
                   // $('#btn_save').html('<i class="fa  fa-spinner"></i>&nbsp;Wait');
    
                    $('.btn_save').prop('disabled', true);
                    //$('.btn_save').html('<i class="fa  fa-spinner"></i>&nbsp;Wait');
    
                    //block multipe request from popup
                    if(isPostRequest==0){
                        isPostRequest=1;
                    }
                    else{
                        return false;
                    }
    
                    if(ajax_url!='' && ajax_url!=undefined){
    
                                var dataString = $("#"+formId).serialize();
                                $.ajax({
                                    type: 'POST',
                                    url: ajax_url,
                                    headers: {
                                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                    },
                    
                                    data:dataString,
                                    dataType: 'json',
                                    success:function(response){	
                                        $('#btn_save').prop('disabled', false);
                                        $('.btn_save').prop('disabled', false);
                                        //lastCallBackItem=ajaxCallbackFunction.pop();
                                        console.log(callBackFunction);                                   
                                        eval(callBackFunction+"(response)");
    
                                        $('#overlay1').fadeOut();
                                        isPostRequest=0;
                                    },
                                    error: function(xhr, ajaxOptions, thrownError) { // if error occured
                                        response =jQuery.parseJSON(xhr.responseText);											
                                                        
                                    }	
                                }); 
    
                    }
                    else{
                        //alert(formId);
                        $('#'+formId).submit();
                    }
                   
                }
                else{
                      // Swal.fire({
                      //     icon: 'warning',
                      //     title: 'Validation Error',
                      //     text: "Please fill all mandatory fields",
                      //     footer: ''
                      // });
                      return false;  
                }
      }
    
    
    
    
    //used in form blades
     $(document).on('focus, keypress, change','.form-control, .form-check-input',function(event) { 
    	    $(this).next('.errormessage').hide();
    });
    
    2. html
    
    <form id="admin_form_1737186047" class="admin_form" >
    
    
    
    <button type="button" class="btn btn-success btn-sm btn_save" id="btn_save" data-form="admin_form"  data-beforeAction="customFunctionBefore"  data-afterAction="customFunctionAfter" data-ajax_url="write you route" data-callBackFunction="customAjaxCallback"><i class="fa fa-save"></i>&nbsp;Save</button>  
    
    
    
    function customFunctionBefore(error){
    
                //write your custom validation
                if(error==1){
                      return 1;
                }
    
    }
    
    function customFunctionAfter(error){
                //write your custom validation
                if(error==1){
                      return 1;
                }
    }
    
    function customAjaxCallback(response){
        //write your custom logic
    }
    
    1. data-beforeAction & data-afterAction are for custom validation
    2. data-ajax_url for ajax form submit
    3. data-callBackFunction for callback after ajax call