Search code examples
jqueryruby-on-railsvalidationruby-on-rails-5formvalidation.io

Rails : why data doesn't get submitted when a custom name attribute is added to the text_field?


The data doesn't get submitted when the name attribute is added in the text_field, When i remove the name attribute it gets submitted fine but the jquery validation doesn't work. I am using jquery formvalidation.io plugin for validation, i want to add a custom name attribute in text_field in order to validate. so far i am finding it difficult to follow, I tried adding like this " 'name'=>'test' " in text_field but no use, hope someone will come up with a solution so that both jquery validation and data submission works fine, thanks.

This is my HTML

<section class="content">
    <%= form_for(tbl_ad_test_overview, :html => {:class => "form-online", :id => "form", :style => "margin-left: 15px; width: 95%;"}) do |f|%>

            <div class="form-group">
                <%= f.label :test, 'Test Number *', class: 'font-color' %>
                <%= f.text_field :test, id: 'test', name:'test', placeholder: 'Test Number', class: 'form-control'%>
                <br>
            </div>

            <div class="form-group">
                <div class="col-lg-12 col-xs-offset-5">
                    <%= f.submit "Submit", id: 'validate', class: 'btn btn-primary'%>
                </div>
            </div>
    <% end %>
</section>

This is my Jquery

$(document).ready(function() {      
 $('#validate').on('click', function(event) {   
  $('#form').formValidation({
    framework : 'bootstrap',
    icon : {
        valid : 'glyphicon glyphicon-ok',
        invalid : 'glyphicon glyphicon-remove',
        validating : 'glyphicon glyphicon-refresh'
    },
    fields : {
        test : {
            validators : {
                notEmpty : {
                    message : 'Please enter a positive number greater than 0'
                },
                stringLength : {
                    min : 1,
                    message : 'Please do enter at least 1 number'
                },
             }
           }
        }
     });
  });   
});

This is required params in controller

def tbl_ad_test_overview_params
    params.require(:tbl_ad_test_overview).permit(:test)  
end

Solution

  • text_field(:post, :title, size: 20)

    # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />

    form helpers generates default names with the help of form_for record and adding a custom name to the form helpers overrides the default name.

    You are overriding the default name(in your case it will be tbl_ad_test_overview[test]) to test which would have lead to failed submission.

    Solution:

    Don't add a custom name, instead use the default name in Jquery validation.

    <%= f.text_field :test, id: 'test', placeholder: 'Test Number', class: 'form-control'%>
    

    and use "tbl_ad_test_overview[test]" instead of test in Jquery validation.