2016-11-01 2 views
1

일부 입력이있는 웹 양식이 있습니다.이 필드의 데이터를 보내는 Ajax가 있습니다. 빈 필드를 확인하기 위해 유효성 검사를 수행합니다. 그러나 코드는 그렇지 않습니다. 작업. 나는 폼을 submiting the default valus로 필드를 쉬고 있다고 생각한다. 검증을 수행하기 전에 submit.please 도움을 받기 전에 유효성 체크를 먼저 할 수있는 방법이 있는가?JQuery : JQuery 유효성 검사 전에 양식을 제출하는 이유

function validate_fields() { 

    var empty_inputs = $('.mandatory').filter(function() { 
     return !$(this).val(); 
    }).length; 
    //Checking if any Empty input or select that has class mandatory 
    if (empty_inputs > 0) { 
     $('form').find('input.mandatory, select.mandatory').each(function() { 
      if ($(this).val() == '' || $(this).val() == null) { //Change the color if empty input or select 
       $(this).css('background-color', '#FFCECE'); 
      } else { 
       $(this).css('background-color', 'transparent'); 
      }; 

     }); 
     return false; 
    } else { 
     return true; 
    } 

} 

$('#button_save').click(function() { 

      $("form").on("submit", function(event) { 

       var status; 
       status = validate_fields(); 
       // if fuction validate_fields return false then Stop submit 
       if (status == false) { 
        return false; 
       } 

       var dt = $(this).serializeArray(); 
       event.preventDefault(); 

       //This Ajax Post the Input data if validation return true. 
       $.ajax({ 

        url: 'send_data.php', 
        type: "post", 
        async: true, 
        data: dt, 
        dataType: 'html', 
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
        success: function(data) { 

        }, 
        error: function(jqXHR, textStatus, errorThrown) { 
         console.log(textStatus, errorThrown); 

        } 

       }); 

      }); 
+0

TRY)과 같은 값 길이의 유효성을 검사하여 코드는 괜찮아 보인다. – GauravKP

답변

1
**you can use this as a Template** 

// Wait for the DOM to be ready 
$(function() { 
    // Initialize form validation on the registration form. 
    // It has the name attribute "registration" 
    $("form[name='registration']").validate({ 
    // Specify validation rules 
    rules: { 
     // The key name on the left side is the name attribute 
     // of an input field. Validation rules are defined 
     // on the right side 
     firstname: "required", 
     lastname: "required", 
     email: { 
     required: true, 
     // Specify that email should be validated 
     // by the built-in "email" rule 
     email: true 
     }, 
     password: { 
     required: true, 
     minlength: 5 
     } 
    }, 
    // Specify validation error messages 
    messages: { 
     firstname: "Please enter your firstname", 
     lastname: "Please enter your lastname", 
     password: { 
     required: "Please provide a password", 
     minlength: "Your password must be at least 5 characters long" 
     }, 
     email: "Please enter a valid email address" 
    }, 
    // Make sure the form is submitted to the destination defined 
    // in the "action" attribute of the form when valid 
    submitHandler: function(form) { 
     form.submit(); 
    } 
    }); 
}); 
+0

감사합니다 @ Ankur.But 내 코드에 적용하는 방법을 이해하지 못합니다. 주어진 코드에 추가하는 것이 좋습니다. 감사합니다. – user5005768

1

난 당신이 양식을 다음과 같이 속성을 확인하기 전에, 코드의 순서를 변경하려면 폼의 기본 동작을 방지 할 일은 무슨 생각 : 여기

는 코드입니다.

$('#button_save').click(function() { 

      $("form").on("submit", function(event) { 
       event.preventDefault(); 
       var status; 
       status = validate_fields(); 

.......... 
    }); 

}); 
1

버튼 클릭 이벤트를 제거하고 직접 양식 제출 이벤트를 사용할 수 있다고 생각합니다.

HTML

<form method="post"> 
    <input type="text" class="mandatory"/> 
    <select class="mandatory"> 
    <option>One</option> 
    <option>Two</option> 
    </select> 

    <button type="submit">Submit</button> 
</form> 

JS

$(function() { 

    function validate_fields() { 

    var empty_inputs = $('.mandatory').filter(function() { 
     return !$(this).val(); 
    }).length; 
    //Checking if any Empty input or select that has class mandatory 
    if (empty_inputs > 0) { 
     $('form').find('input.mandatory, select.mandatory').each(function()  { 
      if ($(this).val() == '' || $(this).val() == null) { //Change the color if empty input or select 
       $(this).css('background-color', '#FFCECE'); 
      } else { 
       $(this).css('background-color', 'transparent'); 
      }; 

     }); 
     return false; 
    } else { 
     return true; 
    } 

    } 

    $("form").on("submit", function(event) { 
    var status; 
    status = validate_fields(); 

    // if fuction validate_fields return false then Stop submit 
    if (status == false) { 
     return false; 
    } 

    var dt = $(this).serializeArray(); 
    event.preventDefault(); 


    //This Ajax Post the Input data if validation return true. 
    $.ajax({ 

     url: 'send_data.php', 
     type: "post", 
     async: true, 
     data: dt, 
     dataType: 'html', 
     contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
     success: function(data) { 

     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
     console.log(textStatus, errorThrown); 

     } 

    }); 

    }); 
}); 

체크 아웃 텍스트 상자 발 (오고 있는지 확인하기 위해이 https://jsfiddle.net/gxj3vL5c/3/

관련 문제