jquery ketchup-plugin for Client-side form-validation:

There are many jquery plugins available for client-side form validation (to validate form before actually submitting it). jquery ketchup-plugin is one of them.

Github: https://github.com/mustardamus/ketchup-plugin

Demo: http://demos.usejquery.com/ketchup-plugin/

Validations provided by plugin:

https://github.com/mustardamus/ketchup-plugin/blob/master/jquery.ketchup.validations.js

Steps:

  1. include css file in your application.css file
 *= require jquery.ketchup 
  1. include js file in your application.js file
 //= require jquery.ketchup.all.min 
  1. Form:
= simple_form_for(@user, :html => {:class => 'ket-validation'}) do |f|
  = f.input :first_name, input_html: { class: "required_field "}
  = f.input :email, input_html: { class: "validate_email" }
  1. initialization on js file: use the class of form and input fields as follows
$(".ket-validation").ketchup({},{
  '.required_field'  : 'required',
  '.validate_email' : 'email'
});

Additional Info:

- To hide all errors

$(".ketchup-error").hide();

- To explicitly call validations on any form on any event

$("#form_id”).ketchup();

Add your own custom-validation:

You can add your own custom validation for any input field:
Following is example of US zip-code validation:

function isValidZip(zip) {
  var pattern = new RegExp(/^\d{5}(-\d{4})?$/);
  return pattern.test(zip);
}

$.ketchup.validation('zip_code', 'Must be a valid Zip Code!', function(form, el, value) {
    return (($.trim(value).length > 0) && !isValidZip(value)) ? false : true
});

$(".ket-validation").ketchup({},{
    '#zip_code'  : 'zip_code'
});

Issue:

1. The validation of required-field fails if only spaces are given as input. This can be solved by overriding it as follows:

$.ketchup.validation('required', 'This field is required.', function(form, el, value) {
    var type = el.attr('type').toLowerCase();
    if(type == 'checkbox' || type == 'radio') {
      return (el.attr('checked') == true);
    } else {
      return ($.trim(value).length != 0);
    }
})

2. It works properly for text and textarea inputs. To apply validation on select, use id of select input

select input

= f.input :type, :prompt => "Select  type",  :collection => (some_collection), input_html: { id: "list_select" }

js code

$.ketchup.validation('lselect', 'You have not selected type!', function(form, el, value) {
     return value.length == 0 ? false : true
});
$(".ket-validation").ketchup({},{
  '#list_select' : 'select'
});

So overall jquery-ketchup plugin is easy to use and customize. Its a good start for beginners to learn.