2

I have a form_tag with some mandatory fields as below

<% form_tag url do %>
  <%= text_field_tag "user[name]", user[:name], :required => true %>
   <%= submit_tag 'Continue', :class => 'submit_button' %>
<% end %>

When i submit the form with just this, it works fine by throwing errors saying that the field is mandatory. But when i bind the submit button with a click event, the required=> true doesnot work anymore. Eg.

$(".submit_button").bind("click",function(e){
   e.preventDefault();
   //Have some code here, I dont want to put field validations here
   $("form").submit();
});

I dont want to put js validations for each and every field, so how can i make the default rails required attibute to work. Please suggest if am missing anything here

Bhavya
  • 572
  • 3
  • 14

1 Answers1

1

When you call e.preventDefault() you prevent the default event handling of the browser for the validation and submit. In your example you only call the form submit explicitly but not the validation.

You can either let the browser handle this, by not calling e.preventDefault and submit explicitly or just call the validation programmatically with

$("form")[0].checkValidity();

(source).

Note that you need to call checkValidity() on the browser element and not on the jQuery element.

Depending on what you want to achieve with your code it might also be handy to use the submit API of the form like in this example, so you do not only link this to the submit button, but call it on form submit.

smallbutton
  • 3,377
  • 15
  • 27