[英]How to validate form for AJAX request using gem 'jquery-validation-rails'
我在Gemfile中有gem'jquery -validation-rails' 。
包含在application.js文件中//= require jquery.validate
然后,我有將驗證添加到某些字段的函數/腳本,例如:
// 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
});
生成的HTML表單:
<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>
並檢查表單提交。
$('form.campaign_form').on('submit', function(){
$('form.campaign_form').valid();
console.log($('form.campaign_form').valid()); // returns TRUE not false even fields with validations are empty
return false; // just to prevent normal form submission
});
為了消除在表單中具有提交按鈕的需要,請使用.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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.