ValidateParams
Params validations for Ruby on Rails.
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.