params_validator

A DSL for validating request parameters, raises exceptions when validation failed. Currently only supports Rails.

Current status is very much alpha, this gem is still under development and not intended to use in production applications.

Installation

Add this to your Gemfile and run bundle install

gem 'params_validator'

Usage

Basic usage:

class WelcomeController < ActionController::Base
  rescue_from ParamsValidator::InvalidParamsException do |exception|
    render :text => 'Error', :status => :bad_request
  end

  validate_params_for :index, { :count => { :_with => [:type_integer] } }
  def index
    @articles = Article.limit(params[:count])
  end
end

Validators

TypeInteger

validate_params_for :index, { :count => { :_with => [:type_integer] } }

Valid:

Invalid:

TypeFloat

validate_params_for :index, { :position => { :_with => [:type_float] } }

Valid:

Invalid:

TypeString

validate_params_for :index, { :name => { :_with => [:type_string] } }

Valid:

Invalid:

TypeHash

validate_params_for :index, { :options => { :_with => [:type_hash] } }

Valid:

Invalid:

TypeArray

validate_params_for :index, { :ids => { :_with => [:type_array] } }

Valid:

Invalid:

Presence

validate_params_for :search, { :q => { :_with => [:presence] } }

Valid:

Invalid:

Whitelist

validate_params_for :search, { :type => { :_with => [:whitelist], :_whitelist: [:documents, :pictures], :_default: :documents } }

Valid:

Invalid:

Validation errors

When validation of parameters fails, this gem is raising a ParamsValidator::InvalidParamsException error which contains an errors hash with further information.

The errors hash is modeled after the Rails model validation errors like this:

{
  :field_name => 'error description',
  :integer_field => 'is not of type integer'
}

As briefly described in the example at the beginning, the easiest way to rescue from validation errors is with a rescue_from block inside your controller, like this:

rescue_from ParamsValidator::InvalidParamsException do |exception|
  render :json => { :errors => exception.errors }, :status => :bad_request
end

Contributing to params_validator

Copyright © 2013 Christof Dorner. See LICENSE.txt for further details.