0.0
Repository is archived
No commit activity in last 3 years
No release in over 3 years
Params validations for Ruby on Rails
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Development

Runtime

~> 4.2.7.1
 Project Readme

ValidateParams

Params validations for Ruby on Rails.

Build Status

Installation

Add this line to your application's Gemfile:

gem 'validate_params'

And then execute:

$ bundle

Usage

In your controller:

class ExamplesController < ApplicationController
  include ValidateParams

  def create
    validate_params! :example
    # [...]
  end
end

You can rescue from exception like this:

class ApplicationController < ActionController::Base
  rescue_from InvalidParamsException do |exception|
    respond_to do |format|
      format.json { render json: { error: exception.to_s }, status: 400 }
      format.html { raise ActionController::RoutingError.new('Not found') }
    end

  end
end

Validate presence

validate_params! :user
validate_params! :user, :token

Validate type and size

validate_params! user: Array
validate_params! user: { type: Array }
validate_params! user: Array, token: String
validate_params! example: { type: Array, size: 2 }

Validate that value is included in a range

validate_params! number: { range: 0..10 }

Validate inclusion

validate_params! example: { in: %w(value1 value2) }

Validate regex

validate_params! example: { regex: /myregex/ }

Validation from custom Proc

validate_params! example: { custom: Proc.new { |value| value == 'a' } }

Set default value

validate_params! example: { default: 'abc' }

Cast

# :Integer :Float or :Array
validate_params! example: { cast: :Integer }

Todo

  • Add a validate_params method (without !) that returns false
  • Config custom exception class

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/rdelandesen/validate_params.

License

The gem is available as open source under the terms of the MIT License.