manishie

client_side_validations gem radio buttons hack

Feb 8th, 2015
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     // client_side_validations rails gem doesn't handle radio buttons, so manually process those with this code
  2.         // this code assumes that your related radio buttons are wrapped in a div with class .radio
  3.         function validate_radio(validations, $radio) {
  4.             var input_wrap = window.ClientSideValidations.forms.new_user.input_tag.split('<span id="input_tag" />');
  5.             var label_wrap = window.ClientSideValidations.forms.new_user.label_tag.split('<label id="label_tag" />');
  6.  
  7.             if ($radio.find('input[type="radio"]:checked').length) {
  8.                 // buttons were checked, so if a previous error message was displayed then get rid of it.
  9.                 $radio.find('.field_with_errors > *').unwrap();
  10.                 $radio.find('.message').remove();
  11.             } else {
  12.                 // no radio buttons in this group were checked so see if we have a presence validator
  13.                 var name = ($radio.find('input[type="radio"]').attr('name'));
  14.                 if (validations.validators[name] && validations.validators[name].presence.length) {
  15.                     var message = '<label class="message">' + validations.validators[name].presence[0].message + '</label>';
  16.  
  17.                     // if we don't already have an error message, then display it
  18.                     if (!$radio.find('field_with_errors').length) {
  19.                         $radio.find('label').first().wrap(label_wrap[0]);
  20.                         $radio.find('> label, > input').wrapAll(input_wrap[0]).parent().append(message);
  21.                     }
  22.                 }
  23.             }
  24.         }
  25.  
  26.         $('form').each(function() {
  27.             var validations = window.ClientSideValidations.forms[$(this).attr('id')];
  28.             if (validations) {
  29.                 $(this).submit(function() {
  30.                     // check all radio buttons on submit
  31.                     $(this).find('.radio').each(function() {
  32.                         validate_radio(validations, $(this));
  33.                     });
  34.                 });
  35.                 $(this).find('.radio input[type="radio"]').blur(function() {
  36.                     validate_radio(validations, $(this).parents('.radio'));
  37.                 });
  38.             }
  39.         });
Add Comment
Please, Sign In to add comment