[英]Rails Way for Form Validation + No Submit Button
Currently I am using jQuery to handle this but it's less than optimal - I can emulate bugs within it quite often (Submit button requiring me to click back into fields multiple times. 目前,我正在使用jQuery来处理此问题,但它并不是最优的-我可以在其中多次模拟错误(“提交”按钮要求我多次单击返回字段。
$(document).ready(function (){
validate();
$('#required_field1, #required_field2, #required_field3, #required_field4, #required_field5, #required_field6').change(validate);
});
function validate(){
if ($('#required_field1').val().length > 0 &&
$('#required_field2').val().length > 0 &&
$('#required_field3').val().length > 0 &&
$('#required_field4').val().length > 0 &&
$('#required_field5').val().length > 0
){
$("input[type=submit]").prop("disabled", false);
}
else {
$("input[type=submit]").prop("disabled", true);
}
}
But it also doesn't feel proper for Rails, at all. 但这对于Rails来说也不适合。 While I understand the concept of data-binding isn't friendly to it, I'm wondering if there is a better way to do this within Rails? 虽然我知道数据绑定的概念并不友好,但我想知道在Rails中是否有更好的方法可以做到这一点?
Currently without it you can Submit a blank page, and get an error immediately, which is much worse experience than this. 当前没有它,您可以提交空白页,并立即得到错误,这比这糟糕得多。
Appreciate any feedback. 感谢任何反馈。
Rails 5 + Bootstrap3(Not that it matters for this.) Rails 5 + Bootstrap3(这并不重要。)
I would use jQuery's serializeArray : 我将使用jQuery的serializeArray :
Eg: 例如:
var params = jQuery("#form_id").serializeArray();
//This should give you form params like:
// [
// {name: "obj[required_field1]", value: ""},
// {name: "obj[required_field2]", value: ""},
// .
// .
// .
// ]
jQuery.each(params, function(i, v) {
if(v["value"].length > 0) {
jQuery("input[type=submit]").prop("disabled", false);
} else {
jQuery("input[type=submit]").prop("disabled", true);
}
});
NOTE: This is just an example to make you understand the concept(as I don't have your HTML/Rails template). 注意:这只是一个使您理解概念的示例(因为我没有HTML / Rails模板)。
EDIT 编辑
Put this logic to change event of each text field. 放置此逻辑以更改每个文本字段的事件。
jQuery("#required_field1, #required_field2, ...").change(function() {
// Above code goes here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.