formvalidation-rails gem

Ademar Tutor | August 05, 2016




In any modern application, one of the requirement is to have a form that has a responsive validation. If your building an application with Ruby on Rails application, and using Bootstrap or Foundation, then it's the best to use Formvalidation.

Add this to your Gemfile: gem 'formvalidation-rails'

Run on terminal: bundle install

On the application.js add:

//= require formvalidation.min
//= require formvalidation/framework/bootstrap.min

In the application.css add:

*= require formvalidation.min

Adding Form Validations

If you have a form like this:

<%= form_for locals[:sponsor], remote: true do |f| %>
  <div class="modal-body">
    <div class="form-group">
      <label>Sponsor Name</label>
      <%= f.text_field :name, class: "form-control", for: "sponsorName" %>
    </div>
    <div class="form-group">
      <label>URL</label>
      <%= f.url_field :url, class: "form-control", for: "sponsorUrl" %>
    </div>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Save changes</button>
  </div>
<% end %>

You can add validations by doing this:

$(document).ready(function() {
  $('#new_sponsor').formValidation({
    framework: 'bootstrap',
    icon: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      'sponsor[name]': {
        verbose: false,
        validators: {
          notEmpty: {
            message: 'Sponsor name is required.'
          },
          remote: {
            message: 'Sponsor already exists.',
            url: '/validate_sponsors',
            data: function(validator, $field, value) {
              return {
                name: validator.getFieldElements('sponsor[name]').val()
              };
            },
            type: 'POST',
            delay: 1000
          }
        }
      },
      'sponsor[url]': {
        verbose: false,
        validators: {
          notEmpty: {
            message: 'Sponsor url must be valid'
          },
          remote: {
            message: 'Sponsor url exists.',
            url: '/validate_sponsors',
            data: function(validator, $field, value) {
              return {
                name: validator.getFieldElements('sponsor[url]').val()
              };
            },
            type: 'POST',
            delay: 1000
          }
        }
      }
    }
  })
  .on('success.form.fv', function(e) {
    e.preventDefault();
  });
});

To learn more about form validations, you can access the API documentation here: http://formvalidation.io/api/