Coder Social home page Coder Social logo

amatsuda / html5_validators Goto Github PK

View Code? Open in Web Editor NEW
304.0 11.0 80.0 369 KB

A gem/plugin for Rails 3, Rails 4, Rails 5, and Rails 6 that enables client-side validation using ActiveModel + HTML5 Form Validation

License: MIT License

Ruby 100.00%
ruby rails html5 validations activerecord activemodel

html5_validators's Introduction

HTML5Validators

Automatic client-side validation using HTML5 Form Validation

What is this?

html5_validators is a gem/plugin for Rails 3+ that enables automatic client-side validation using ActiveModel + HTML5. Once you bundle this gem on your app, the gem will automatically translate your model validation code into HTML5 validation attributes on every form_for invocation unless you explicitly cancel it.

Features

PresenceValidator => required

  • Model
class User
  include ActiveModel::Validations
  validates_presence_of :name
end
  • View
<%= f.text_field :name %>

other text_fieldish helpers, text_area, radio_button, and check_box are also available

  • HTML
<input id="user_name" name="user[name]" required="required" type="text" />
  • SPEC

http://dev.w3.org/html5/spec/Overview.html#attr-input-required

PresenceValidator

LengthValidator => maxlength

  • Model
class User
  include ActiveModel::Validations
  validates_length_of :name, maximum: 10
end
  • View
<%= f.text_field :name %>

text_area is also available

  • HTML
<input id="user_name" maxlength="10" name="user[name]" size="10" type="text" />
  • SPEC

http://dev.w3.org/html5/spec/Overview.html#attr-input-maxlength

NumericalityValidator => max, min

  • Model
class User
  include ActiveModel::Validations
  validates_numericality_of :age, greater_than_or_equal_to: 20
end
  • View (be sure to use number_field)
<%= f.number_field :age %>
  • HTML
<input id="user_age" min="20" name="user[age]" size="30" type="number" />
  • SPEC

http://dev.w3.org/html5/spec/Overview.html#attr-input-max http://dev.w3.org/html5/spec/Overview.html#attr-input-min

NumericalityValidator

And more (coming soon...?)

๐Ÿšง

Disabling automatic client-side validation

There are four ways to cancel the automatic HTML5 validation.

1. Per form (via form_for option)

Set auto_html5_validation: false to form_for parameter.

  • View
<%= form_for @user, auto_html5_validation: false do |f| %>
  ...
<% end %>

2. Per model instance (via model attribute)

Set auto_html5_validation = false attribute to ActiveModelish object.

  • Controller
@user = User.new auto_html5_validation: false
  • View
<%= form_for @user do |f| %>
  ...
<% end %>

3. Per model class (via model class attribute)

Set auto_html5_validation = false to ActiveModelish class' class variable. This configuration will never be propagated to inherited children classes.

  • Model
class User < ActiveRecord::Base
  self.auto_html5_validation = false
end
  • Controller
@user = User.new
  • View
<%= form_for @user do |f| %>
  ...
<% end %>

4. Globally (via HTML5Validators module configuration)

Set config.enabled = false to Html5Validators module. Maybe you want to put this in your test_helper, or add a controller filter as follows for development mode.

  • Controller
# an example filter that disables the validator if the request has {h5v: 'disable'} params
around_action do |controller, block|
  h5v_enabled_was = Html5Validators.enabled
  Html5Validators.enabled = false if params[:h5v] == 'disable'
  block.call
  Html5Validators.enabled = h5v_enabled_was
end

Supported versions

  • Ruby 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2, 3.3 (trunk)

  • Rails 3.2.x, 4.0.x, 4.1, 4.2, 5.0, 5.1, 5.2, 6.0, 6.1, 7.0, 7.1 (edge)

  • HTML5 compatible browsers

Installation

Put this line into your Gemfile:

gem 'html5_validators'

Then bundle:

% bundle

Notes

When accessed by an HTML5 incompatible legacy browser, these extra attributes will just be ignored.

Todo

  • more validations

Copyright

Copyright (c) 2011 Akira Matsuda. See MIT-LICENSE for further details.

html5_validators's People

Contributors

amatsuda avatar dialbird avatar hshimoyama avatar kv109 avatar lucas-nelson avatar sandipransing avatar sinsoku avatar tricknotes avatar ursm avatar ykzts avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

html5_validators's Issues

Support for form_with

form_with, introduced in Rails 5.1 can generate form tags based on URLs, scopes or models (before the alternatives were form_for for model instances and form_tag for custom URLs). When including a model, the gem could also generate html validators for it.

undefined method

I get:

undefined method `auto_html5_validation' for #Class:0x007f11bd92f6a0

My guess is that you require some javascript file to be added to the manifest when not using //= require_tree .

Doesn't work with other ORMs besides ActiveRecord

I'm using Mongoid as my object mapper. So since I don't require the ActiveRecord railtie in my app the ActiveRecord on_load hook doesn't run and the ActiveModel helper methods don't get loaded in.

Any chance the loading code could be changed to work with any ActiveModel based mapper?

undefined method `auto_html5_validation' for Active Model

From my spider test:

[979faece-c1e5-4d78-ac39-0b73b12863c4] [299:68.43] ActionView::Template::Error (undefined method `auto_html5_validation' for Patchinfo:Class):
[979faece-c1e5-4d78-ac39-0b73b12863c4] [299:68.43]     11:             %strong
[979faece-c1e5-4d78-ac39-0b73b12863c4]     12:               = f.label(:packager, 'Packager:')
[979faece-c1e5-4d78-ac39-0b73b12863c4]     13:             %br/
[979faece-c1e5-4d78-ac39-0b73b12863c4]     14:             = f.text_field :packager, required: true
[979faece-c1e5-4d78-ac39-0b73b12863c4]     15:             :javascript
[979faece-c1e5-4d78-ac39-0b73b12863c4]     16:               $("#packager").autocomplete({source: '#{url_for controller: 'user', action: 'autocomplete'}', search: function(event, ui) {
[979faece-c1e5-4d78-ac39-0b73b12863c4]     17:                 $(this).addClass('loading-spinner');
[979faece-c1e5-4d78-ac39-0b73b12863c4] [299:68.43]   
[979faece-c1e5-4d78-ac39-0b73b12863c4] [299:68.43] app/views/webui/patchinfo/_form.html.haml:14:in `block in _app_views_webui_patchinfo__form_html_haml__1383717022713791384_47354342968160'
[979faece-c1e5-4d78-ac39-0b73b12863c4] app/views/webui/patchinfo/_form.html.haml:2:in `_app_views_webui_patchinfo__form_html_haml__1383717022713791384_47354342968160'
[979faece-c1e5-4d78-ac39-0b73b12863c4] app/views/webui/patchinfo/edit.html.haml:3:in `_app_views_webui_patchinfo_edit_html_haml__1907723402339578054_47354343006520'
[979faece-c1e5-4d78-ac39-0b73b12863c4] config/initializers/wrap_parameters.rb:38:in `call'
[979faece-c1e5-4d78-ac39-0b73b12863c4] test/functional/webui/spider_test.rb:99:in `crawl'
[979faece-c1e5-4d78-ac39-0b73b12863c4] test/functional/webui/spider_test.rb:161:in `test_spider_as_admin'
[979faece-c1e5-4d78-ac39-0b73b12863c4] test/test_helper.rb:118:in `block in __run'
[979faece-c1e5-4d78-ac39-0b73b12863c4] test/test_helper.rb:118:in `map'
[979faece-c1e5-4d78-ac39-0b73b12863c4] test/test_helper.rb:118:in `__run'

It only fails for Active Model, not for Active Record.

"length" validation should add "required" attribute automatically

Hi!

I've noticed that

validates :first_name, length: { minimum: 2, maximum: 50 }

translates to

<input maxlength="50" minlength="2" size="50" type="text">

To be 100% accurate with actual model validation, it should translate to
<input required="required" maxlength="50" minlength="2" size="50" type="text">

If you agree, I could prepare a pull request with that, are you interested?

inclusion support

The following Rails code:

# User model
validates :state, inclusion: { in: ['unconfirmed', 'confirmed', 'locked', 'deleted', 'subaccount'] }

# user edit view
= f.text_field :state

can be translated into the following html code:

<input id="user_state" name="user[state]" type="text" pattern="(unconfirmed)|(confirmed)|(locked)|(deleted)|(subaccount)"/>

Can I send a PR?

Related to #23

Highlight all fields that fail validation at the same time

It would be nice if, instead of a single field failing validation being highlighted, the user fixes that field, and then attempts to submit again and they get the next field that failed, that all fields that fail validation are highlighted at the same time. This will provide a better user experience and less steps to get a proper input from the user.

does not work for select

validates :country_code, presence: true

translates to

<select name="user[country_code]">

instead of

<select required="required" name="user[country_code]">

Should support non ActiveRecord::Base classes

The class method auto_html5_validation is added to ActiveRecord::Base, when imho it should be in ActiveModel::Model. This would allow auto_html5_validation to work with objects that just include ActiveModel::Model. (Which is often done for custom form objects, etc.)

Regexp support

Hi @amatsuda and thanks for great gem!

I want to know do you have any plans to support Regexp in a future? Seems like this library really helps to avoid duplication between client and server, but with regexp I have to copy them anyway.

Or, maybe you have any advice for that?

I have for example, validation in backend with

value =~ /\A(4|9)\d{7}\Z/

and for frontend:

<%= f.telephone_field(:phone,
         placeholder: 'Mobile',
         pattern: '^[49]\d{7}$') %>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.