user588324
user588324

Reputation: 310

How to show validations error on submit form via ajax?

My form is little complex, everything is on landing page welcome/index.html.erb.

This form has two tabs: products and users.

Under products tab there are features like:

For each product there are options like:

When I click on create new product there is div open which has form for new product.

I tried using client_side_validation but no success (from google search it looks like this gem is not supported for rails 3.2.13).

How can I show validation error when I submit my form using jquery?

this.submit(function() {
  //$('#createPolicy').slideToggle();
  $.post(this.action, $(this).serialize(), null, "script");
  return false;
})
return this;

Thanks for your help.

Upvotes: 0

Views: 529

Answers (1)

Joe Half Face
Joe Half Face

Reputation: 2333

You don't need ajax POST at all. If submit function returns falase, page won't be reloaded.

$('#button').submit(function() {
  if($('input#field_1').val().length===0){
  $('.errors').text("Can't be blank") } 
  return false
  else if(#more conditionals) {

  } #...
  else{
return true}
})

This way validation works both user-side and server-side. If you want to do it through AJAX request, you should provide response of method on case true,which also needs to rework content of page, on case false, providing errors meassages. A lot of work to do. I believe request is needed only when your validation is based on DB data, such as uniqueness.

Upvotes: 1

Related Questions