Integrating with client_side_validations

taavo edited this page Nov 13, 2012 · 2 revisions

As of #211, client_side_validations can tell what fields you specify in your nested_form blueprints, and will therefore automatically generate javascript validators for them. As of #199, client_side_validations can match those validators to new items added by nested fields. So integration looks like this:

  1. Install and set up client_side_validations and nested_form (> 0.3.1). If you're using simple_form or formtastic, make sure to also install and configure client_side_validations-simple_form or client_side_validations-formtastic.

  2. Make sure your form builder is set up properly in client_side_validations. Depending on your form builder, you may need some js like this:

ClientSideValidations.formBuilders['NestedForm::Builder'] = ClientSideValidations.formBuilders['ActionView::Helpers::FormBuilder'];

or like this:

ClientSideValidations.formBuilders['NestedForm::SimpleBuilder'] = ClientSideValidations.formBuilders['SimpleForm::FormBuilder'];

or like this:

ClientSideValidations.formBuilders['NestedForm::FormtasticBuilder'] = ClientSideValidations.formBuilders['Formtastic::FormBuilder'];

I add this js to a file named something like app/assets/javascripts/rails.validations.nested_form.js, and include it in my application.js manifest after both client_side_validations javascripts:

//= require rails.validations
//= require rails.validations.simple_form
//= require rails.validations.nested_form
  1. Make a nested_form_for with :validate => true. At this point you should be getting client side validations for nested fields that exist when the form loads, but not for new fields.

  2. Enable client_side_validations for your new fields by adding some javascript like this:

$('form').on('nested:fieldAdded', function(event) {
  $(event.target).find(':input').enableClientSideValidations();
});