简体   繁体   中英

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:

  • create new product
  • show list of products

For each product there are options like:

  • add user to product

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM