如何使用gem'jquery-validation-rails'验证AJAX请求的表单

时间:2018-08-14 09:09:48

标签: javascript jquery ruby-on-rails jquery-validate

我在Gemfile中有 gem'jquery-validation-rails'

将其包含在application.js文件Pipeline

然后我有一些函数/脚本,它们将验证添加到某些字段,例如:

//= require jquery.validate

生成的HTML表单:

// Field names from FORM
function validateCampaignForm(){
   var $form = $('form.user_form');
   $form.validate({
      rules: {
         "user[title]": {required: true, maxlength: 80},
         "user[content]": {required: true, maxlength: 80},

         }
    });
}
// Load
validateCampaignForm();


// Save button on click
$('a.save-form').on('click', function(){
  // should validates field
});

为了进行测试,我试图将“保存”(链接)更改为“提交类型”按钮:

并检查表单提交。

<form class="user_form" action="/users/1110212666" accept-charset="UTF-8" method="post" novalidate="novalidate">
  <div class="row">
    <label>Title</label>
    <input class="required" type="text" value="We saved your cart" name="user[title]" id="user_title">
  </div>
  ...other fields....

  <a class="button primary save-form" href="#">Save Settings</a>
</form>

1 个答案:

答案 0 :(得分:1)

要消除在表单中使用“提交”按钮的必要,请使用.valid()触发验证

<form class="campaign_form" action="/users/1110212666" accept-charset="UTF-8" method="post" novalidate="novalidate">
  <div class="row">
    <label>Title</label>
    <input class="required" type="text" value="We saved your cart" name="user[title]" id="user_title">
  </div>
  ...other fields....

  # IMPORTANT NOTE: <a> or other elements aside from button type="submit" can only trigger the validation. 
  // <a class="button primary save-form" href="javascript:;">Save Settings</a>
  <button type="submit" class="save-form">Save Settings</button>
</form>

使用jquery-validate进行验证

// initializes validation
 $('.user_form').validate({
    rules: {
       "user[title]": {required: true, maxlength: 80},
       "user[content]": {required: true, maxlength: 80}
       }
  });

// on click validation of user form
$('.save-form').on('click', function(e){
  e.preventDefault(); // to prevent form from normal submission
  $('.user_form').valid();
});

// other way (catch on form submission)
$('form.campaign_form').on('submit', function(e){
  e.preventDefault();
  $('.user_form').valid();
});