• Stars
    star
    306
  • Rank 131,400 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 13 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Collection of ActiveModel/ActiveRecord validators

ActiveValidators CircleCI

Description

ActiveValidators is a collection of off-the-shelf and tested ActiveModel/ActiveRecord validations.

Verify authenticity of this gem

ActiveValidators is cryptographically signed. Please make sure the gem you install hasn’t been tampered with.

Add my public key (if you haven’t already) as a trusted certificate:

gem cert --add <(curl -Ls https://raw.githubusercontent.com/franckverrot/activevalidators/master/certs/franckverrot.pem)

gem install activevalidators -P MediumSecurity

The MediumSecurity trust profile will verify signed gems, but allow the installation of unsigned dependencies.

This is necessary because not all of ActiveValidators’ dependencies are signed, so we cannot use HighSecurity.

Requirements

  • Rails 5.1+
  • Ruby 2.4+

Installation

gem install activevalidators

This projects follows Semantic Versioning a.k.a SemVer. If you use Bundler, you can use the stabby specifier ~> safely.

What it means is that you should specify an ActiveValidators version like this :

gem 'activevalidators', '~> 5.1.0' # <-- mind the patch version

Once you have require'd the gem, you will have to activate the validators you want to use as ActiveValidators doesn't force you to use them all :

# Activate all the validators
ActiveValidators.activate(:all)

# Activate only the email and slug validators
ActiveValidators.activate(:email, :slug)

# Activate only the phone
ActiveValidators.activate(:phone)

ActiveValidators.activate can be called as many times as one wants. It's only a syntactic sugar on top a normal Ruby require.

In a standard Ruby on Rails application, this line goes either in an initializer (config/initializers/active_validators_activation.rb for example), or directly within config/application right inside your MyApp::Application class definition.

Usage

In your models, the gem provides new validators like email, or url:

class User
  validates :company_siren, :siren       => true
  validates :email_address, :email       => true # == :email => { :strict => false }
  validates :link_url,      :url         => true # Could be combined with `allow_blank: true`
  validates :password,      :password    => { :strength => :medium }
  validates :postal_code,   :postal_code => { :country => :us }
  validates :twitter,       :twitter     => true
  validates :twitter_at,    :twitter     => { :format => :username_with_at }
  validates :twitter_url,   :twitter     => { :format => :url }
  validates :user_phone,    :phone       => true
end

class Identification
  validates :nino, :nino => true
  validates :sin,  :sin  => true
  validates :ssn,  :ssn  => true
end

class Article
  validates :slug,            :slug => true
  validates :expiration_date, :date => {
                                          :after => -> (record) { Time.now },
                                          :before => -> (record) { Time.now + 1.year }
                                        }
end

class Device
  validates :ipv4, :ip => { :format => :v4 }
  validates :ipv6, :ip => { :format => :v6 }
end

class Account
  validates :any_card,        :credit_card => true
  validates :visa_card,       :credit_card => { :type => :visa }
  validates :credit_card,     :credit_card => { :type => :any  }
  validates :supported_card,  :credit_card => { :type => [:visa, :master_card, :amex] }
end

class Order
  validates :tracking_num, :tracking_number => { :carrier => :ups }
end

class Product
  validates :code, :barcode => { :format => :ean13 }
end

Exhaustive list of supported validators and their implementation:

  • barcode : based on known formats (:ean13 only for now)
  • credit_card : based on the credit_card_validations gem
  • date : based on the date_validator gem
  • email : based on the mail gem
  • hex_color : based on a regular expression
  • ip : based on Resolv::IPv[4|6]::Regex
  • nino : National Insurance number (only for UK). Please note that this validation will not accept temporary (such as 63T12345) or administrative numbers (with prefixes like OO, CR, FY, MW, NC, PP, PY, PZ).
  • password : based on a set of regular expressions
  • phone : based on a set of predefined masks
  • postal_code: based on a set of predefined masks
  • regexp : uses Ruby's Regexp.compile method
  • respond_to : generic Ruby respond_to
  • siren : SIREN company numbers in France
  • slug : based on ActiveSupport::String#parameterize
  • sin : Social Insurance Number (only for Canada). You may also allow permanent resident cards (such cards start with '9') or business numbers (such numbers start with '8'): :sin => {:country => :canada, :country_options => {allow_permanent_residents: true, allow_business_numbers: true}}
  • ssn : Social Security Number (only for USA).
  • tracking_number: based on a set of predefined masks
  • twitter : based on a regular expression
  • url : based on a regular expression

Handling error messages

The validators rely on ActiveModel validations, and will require one to use its i18n-based mechanism. Here is a basic example:

# user.rb

class User < ActiveRecord::Base
  validates :email, email: {message: :bad_email}
end
# en.yml

en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            email:
              bad_email: "your error message"

Todo

Lots of improvements can be made:

  • Implement new validators
  • ...

Note on Patches/Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don't break it in a future version unintentionally.
  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.

Contributors

Please checkout AUTHORS.md to see who contributed. Get involved!

Copyright

Copyright (c) 2010-2018 Franck Verrot. MIT LICENSE. See LICENSE for details.

More Repositories

1

terraform-provider-stripe

A Terraform Provider for Stripe
Go
238
star
2

holycorn

Community version of the PostgreSQL multi-purpose Ruby Foreign Data Wrapper
C
167
star
3

EmulationResources

Collection of resources for emulator developers
HTML
86
star
4

no_querying_views

No more querying views in your Rails apps
Ruby
60
star
5

git_fdw

PostgreSQL Git Foreign Data Wrapper
C
46
star
6

clamav-client

ClamAV::Client connects to a Clam Anti-Virus clam daemon and send commands
Ruby
40
star
7

trek

Trek is a CLI/ncurses explorer for HashiCorp Nomad clusters.
Go
32
star
8

blake2

BLAKE2 - fast secure hashing - for Ruby
Ruby
28
star
9

mruby-r

mruby-r: Use (m)Ruby for returning data to R
Ruby
26
star
10

fruby

A French version of Ruby (based on mruby)
C
19
star
11

rb_import

rb_import: ES6 `import`/Node's `require`, for Ruby.
Ruby
19
star
12

codes-bic-france

Code BIC des Banques Françaises
13
star
13

arnoldc.rb

The ugliest implementation of the Arnold Schwarzenegger based programming language, in Ruby.
Ruby
10
star
14

terraform-provider-homebrew

Terraform provider for Homebrew
Go
8
star
15

ers

ers - ERb-like templating engine for Rust
Rust
8
star
16

yamlsh

Interactive REPL for authoring YAML files
Ruby
8
star
17

git-mine-commit

Mine your git commit hash (SHA1) because you know... YOLO
Shell
7
star
18

tictactoe-elm

Tic Tac Toe with Elm
JavaScript
7
star
19

paybox

Paybox's payment gateway -- UNMAINTAINED
Ruby
7
star
20

awesome-rfcs

Curated list of RFCs / Community Processes
6
star
21

isolate

Prevent processes from accessing unauthorized files
C
6
star
22

gendarme

Gendarme checks for preconditions and postrelations on the methods you want it to monitor.
Ruby
6
star
23

wtf

Secret project, sssshhhh
Ruby
5
star
24

namos

🚀 Naming and Synchronization in a Decentralized Computer System 🚀 (Author: David P. Reed)
CSS
5
star
25

tweetnacl

TweetNaCl Ruby C-extension
C
5
star
26

OpenNICSwitcher

OSX app that makes using an OpenNIC DNS server a no-brainer (under development)
Ruby
4
star
27

adversarial-ml

Adversarial Machine Learning
3
star
28

bmmlexporter

Simple exporter from Bmml files
Ruby
3
star
29

Reader.elm

RSS front-end a-la Google Reader created with Elm (elm-lang.org)
Elm
3
star
30

postgresql-performance-subquery-vs-join

R
2
star
31

game-of-life-in-elm

Game of Life in Elm
HTML
2
star
32

raven

Consul-based Control Plane for Envoy Proxy
Go
2
star
33

dependency_revealer

Extract dependencies info from a Gemfile (and a Gemfile.lock)
Ruby
2
star
34

gem-license-check

License reporter and checker for your Ruby projects
Ruby
2
star
35

TCL

Des données, des transports en communs lyonnais.
JavaScript
1
star
36

golo-hs

Playground, parsing Golo with Haskell's attoparsec
Haskell
1
star
37

Reader.ex

REST API for Reader.elm
Elixir
1
star
38

TaskRunner

Experimental Task Runner in Haskell
Haskell
1
star
39

fr-lang

Functional Ruby Programming Language Experiment
Ruby
1
star
40

live-note

Live-Note
Python
1
star
41

dotfiles

Vim Script
1
star
42

dalek

dalek is an experimental (and unfinished) campfire bot that can self-upgrade, watch the video for more information
Ruby
1
star
43

ar2json

ActiveRecord extension that uses the database to build a record's JSON representation
Ruby
1
star
44

lmftfy

Let Me Fork That For You, the best way to get your patch applied to your favorite project
Ruby
1
star
45

CodeBeautifier

This Rails plugin modifies the content that goes out your Rails application and format it nicely.
Ruby
1
star
46

gemtalker

Talk to Gemcutter's API using XMPP/Google Talk [Invite [email protected] to chat in GTalk]
Python
1
star
47

exportable

exportable will help you export arrays of objects and reuse the export definitions across your classes
Ruby
1
star
48

hudson-git-flow

discover new github topic/feature branches and add as Hudson jobs
Ruby
1
star
49

chrust

Changes the current Rust
Shell
1
star
50

heroku-cedar-examples

Ruby, NodeJS and Clojure app examples to run on Heroku's Cedar stack
Shell
1
star
51

pivotbot

A Pivotal Tracker Command Line Tool
Haskell
1
star
52

autostopper

Simple script that stops your running AWS EC2 instances.
Ruby
1
star
53

jruby-experiments

Some personal JRuby experiments
Ruby
1
star