简体   繁体   中英

How to validate form for AJAX request using gem 'jquery-validation-rails'

I have gem 'jquery-validation-rails' in Gemfile.

Included it in application.js file //= require jquery.validate

Then I have function/scripts that adds validation to certain fields, as:

// Field names from FORM
function validateCampaignForm(){
   var $form = $('form.user_form');
   $form.validate({
      rules: {
         "user[title]": {required: true, maxlength: 80},
         "user[content]": {required: true, maxlength: 80},

         }
    });
}
// Load
validateCampaignForm();


// Save button on click
$('a.save-form').on('click', function(){
  // should validates field
});

Generated HTML Form:

<form class="user_form" action="/users/1110212666" accept-charset="UTF-8" method="post" novalidate="novalidate">
  <div class="row">
    <label>Title</label>
    <input class="required" type="text" value="We saved your cart" name="user[title]" id="user_title">
  </div>
  ...other fields....

  <a class="button primary save-form" href="#">Save Settings</a>
</form>

Just for testing, I tried to changed the Save (link), to a submit type button:

And checking the form submission.

   $('form.campaign_form').on('submit', function(){
      $('form.campaign_form').valid();
      console.log($('form.campaign_form').valid()); // returns TRUE not false even fields with validations are empty
      return false; // just to prevent normal form submission
   });

To eliminate the need to have a submit button within the form, use .valid() to trigger a validation

<form class="campaign_form" action="/users/1110212666" accept-charset="UTF-8" method="post" novalidate="novalidate">
  <div class="row">
    <label>Title</label>
    <input class="required" type="text" value="We saved your cart" name="user[title]" id="user_title">
  </div>
  ...other fields....

  # IMPORTANT NOTE: <a> or other elements aside from button type="submit" can only trigger the validation. 
  // <a class="button primary save-form" href="javascript:;">Save Settings</a>
  <button type="submit" class="save-form">Save Settings</button>
</form>

Validation using jquery-validate

// initializes validation
 $('.user_form').validate({
    rules: {
       "user[title]": {required: true, maxlength: 80},
       "user[content]": {required: true, maxlength: 80}
       }
  });

// on click validation of user form
$('.save-form').on('click', function(e){
  e.preventDefault(); // to prevent form from normal submission
  $('.user_form').valid();
});

// other way (catch on form submission)
$('form.campaign_form').on('submit', function(e){
  e.preventDefault();
  $('.user_form').valid();
});

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