Reputation: 3615
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>
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
});
Upvotes: 1
Views: 1654
Reputation: 6531
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();
});
Upvotes: 2