Rails Error Messages on Fields and other Customizations

Rails Error Messages on Fields and other Customizations

If you wanted to show an error message with the field and also you wanted to highlight that particular field. Here you have to create a new file inside  config/initializers folder of your application, make sure to restart your application if you are making any sort of changes inside the config folder.

Here we are basically adding a class "error" to the field and showing a span with the error message.

rails-fields-with-errors.rb

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|    class_attr_index = html_tag.index 'class="'    errors = Array(instance.error_message).join(',')    if !class_attr_index.nil?      html_tag.insert class_attr_index+7, 'error '    else      html_tag.insert html_tag.index('>'), ' class="error"'    end    %(#{html_tag} #{errors}).html_safe  end
You can add your css for example.
.error{border:2px solid red ;}  .validation-error{color:red;}        
You can add more customizations like you can remove the class error when someone start typing in the error field, you can use the following code

jQuery(document).ready(function() {      jQuery('.error').keyup(function(){jQuery(this).removeClass('error');      jQuery(this).next('span').html(" ");      });  });
All these are things are basic , Use and play with it !!

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Remove duplicates from a JavaScript Array

Sending Binary Data over the Network with Json