2013-02-19 80 views
0

我不希望客戶端驗證在模糊輸入時進行驗證,只是當我點擊保存時。rails client_side_validations only hit hit save

這可能嗎? 我該怎麼做?

我只是一些簡單的驗證(空的,基本上)...而我正在考慮用手寫它..它值得嗎?

回答

1

您可以使用純Javascript或藉助任何JQuery/Prototype和類似框架輕鬆完成此操作。

這裏是我用jQuery

<html> 
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
    <body> 
     <form id="my_form" action="http://google.com?q=ruby" method="GET"> 
      <input type="text" name="first_name" placeholder="First Name" /> <br/> 
      <input type="text" name="last_name" placeholder="Last Name" /> <br/> 
      <input type="text" name="city" placeholder="City" /> <br/> 
      <input id="form_button" type="button" value="Submit"/> 
     </form> 
    </body> 
</html> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#form_button").on('click', function() { 
      var form_valid = true; 
      $("#my_form > input[type='text']").each(function() { 
       if(this.value == "") { 
        var error_span_present = $(this).next("span").length != 0; 
        if(!error_span_present) { 
         $("<span style='color:red;'>" + $(this).attr("placeholder") + " cannot be Blank </span>").insertAfter($(this)); 
        } 
        else { 
         $(this).next("span").html($(this).attr("placeholder") + " cannot be Blank"); 
        } 
        form_valid = false; 
       } 
       else { 
        if($(this).next("span").length != 0) { 
         $(this).next("span").remove(); 
        } 
       } 
      }); 
      if(form_valid){ 
       $("#my_form").submit(); 
      } 
     }); 
    }); 
</script> 

嘗試了代碼以下是演示此代碼JSFiddle

希望這會有幫助

+0

其實,我只是留下它與HTML5驗證和一些CSS。無論如何感謝您的回答,它應該=)歡呼 – caarlos0 2013-02-19 20:33:03

相關問題