gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:19:12 29 4
gpt4 key购买 nike

我在 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();
});

关于javascript - 如何使用 gem 'jquery-validation-rails' 验证 AJAX 请求的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51837750/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com