无论模型中的验证器如何,表单有效性都会不断返回true

时间:2015-10-31 04:23:36

标签: jquery ruby-on-rails forms validation paperclip

我正在使用jQuery隐藏和禁用提交按钮,直到使用Paperclip的validates_attachment_file_name

验证表单

单击表单后立即显示该按钮,并且无论选择哪个文件,都会继续显示该按钮。

我在表单上调用了.checkValidity(),发现它一直在返回true。一旦单击表单,并在选择(任何)文件时再次单击。

Ruby模型:

has_attached_file :file
validates_attachment_file_name :file, matches: [/string\Z/]

jQuery的:

$('#form').bind('change click', function() {
    if ($(this).valid()) {
      $('#submit').attr('disabled', false);
      $('#submit').show();
    } else {
      $('#submit').attr('disabled', true);
      $('#submit').hide();
    }
  });

我错过了什么?

1 个答案:

答案 0 :(得分:1)

您的ajax在哪里?

您正在调用javascript函数来验证ruby值。

您应该知道, javascript 是客户端, ruby​​ 是服务器端。 JS只能阅读"DOM" (Document Object Model)((HTML))中的字面打印内容。

因此,你的JS完全是假的:

 $('#form').bind('change click', function() { // on FORM change (not file input)
    if ($(this).valid()) { // if FORM valid
      $('#submit').attr('disabled', false); // enable submit
      $('#submit').show(); // show submit
    } else {
      $('#submit').attr('disabled', true); //disable submit
      $('#submit').hide();  //hide submit
    }
  });

上述内容涉及表单。您需要处理表单的提交和响应。这里有一个很好的例子:http://firststopcosmeticshop.herokuapp.com(点击"登录",提交并查看返回的数据)

enter image description here

解决问题的方法是使用" ajax"将数据发送到您的服务器,获取响应并使用它操纵DOM。

-

你最好这样做:

#app/assets/javascripts/application.js
$(document).on("submit", "#form", function(e){
   e.preventDefault();
   $(this).find("submit").attr('disabled', true);

   $.ajax({
      url: $(this).attr("action"),
      data: $(this).serialize(),
      success: function(data){
          // do something when successful
      },
      error: function(data) {
          // this is where validation errors will show
      }
   });
});

您必须使用适当的控制器操作进行备份:

#app/controllers/your_controller.rb
class YourController < ApplicationController
   def create
      @object = Object.new object_params
      @object.save
      # conditional response here
   end
end

-

现在,您还有一个问题,即Javascript无法通过XML上传文件。有一项解决此问题的技术(jquery-file-upload),我们使用了here(您必须注册并转到配置文件上传照片):

enter image description here

如果需要,我可以详细介绍。

基本上,您只需将上述 ajax 功能替换为.fileupload

$('#avatar').fileupload({

        url: '/profile/' + $(this).attr('data_id'),
        dataType: 'json',
        type: 'post',

Great example here