Skip to content
This repository has been archived by the owner on Jun 28, 2023. It is now read-only.

rdelandesen/validate_params

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

Params validations for Ruby on Rails.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published