Client Side Validations made easy for Ruby on Rails
Client Side Validations made easy for Ruby on Rails
ClientSideValidations made easy for your Rails 7.2 and 8.x applications!
Add the following line to your Gemfile:
gem 'client_side_validations'Then run bundle install
Please run spring stop if you are using Spring
Next you need to run the generator:
rails g client_side_validations:installThis will install the initializer:
config/initializers/client_side_validations.rbInstructions depend on your technology stack.
ClientSideValidations no longer depends on jQuery.
If you previously installed jquery-rails, jquery_ujs, or custom jQuery startup code only for ClientSideValidations, you can remove that integration when upgrading to 24.x.
Add the following package:
yarn add @client-side-validations/client-side-validationsThen add the following line to your app/javascript/packs/application.js pack:
// If you are using `import` syntax
import '@client-side-validations/client-side-validations'
// If you are using `require` syntax
require('@client-side-validations/client-side-validations')If you are using Turbo, use the
import syntax and make sure that @client-side-validations/client-side-validations
is imported after @hotwired/turbo-rails, so ClientSideValidations can properly detect
window.Turbo and attach its event handlers.
If you are using Turbolinks 5.2,
use the require syntax and make sure that @client-side-validations/client-side-validations
is required after Turbolinks.start(), so ClientSideValidations can properly
detect window.Turbolinks and attach its event handlers.
Add the following to your app/assets/javascripts/application.js file:
//= require rails.validationsIf you are using Turbolinks,
make sure that rails.validations is required after turbolinks, so
ClientSideValidations can properly attach its event handlers.
If you need to copy the asset files from the gem into your project, run:
rails g client_side_validations:copy_assetsNote: If you run copy_assets, you will need to run it again each time you update this project.
If you are upgrading to 24.x, update your integration code to use the ClientSideValidations object directly.
The old jQuery plugin methods are removed. Use the DOM-first public API instead:
ClientSideValidations.enable(form)
ClientSideValidations.validate(form)
ClientSideValidations.isValid(form, validators)
ClientSideValidations.disable(form)
ClientSideValidations.reset(form)These methods accept native DOM elements and DOM collections. They do not accept jQuery objects or CSS selector strings.
Custom validators, form builders, and callbacks now receive native DOM nodes instead of jQuery wrappers. Update any custom code to use DOM APIs such as .value, .form, .closest(), and querySelector().
Local validators are called as (element, options). Form callbacks receive (form, eventData), and element callbacks receive either (element, message, callback) or (element, callback) depending on the event.
All runtime-owned validation state attributes are now namespaced under csv. If you read or write these attributes in custom selectors, callbacks, or validators, update them to the scoped names:
data-changed => data-csv-changed
data-valid => data-csv-valid
data-validate => data-csv-validate
data-not-locally-unique => data-csv-not-locally-uniqueThe matching dataset properties are element.dataset.csvChanged, element.dataset.csvValid, element.dataset.csvValidate, and element.dataset.csvNotLocallyUnique. csvChanged is stored as the string values 'true' and 'false'.
jQuery namespaced events are removed. Events are now plain native DOM custom events. If your application listens to or unbinds events using jQuery-style namespacing, you must update those calls.
Before:
$(form).on('form:validate:before.ClientSideValidations', handler)
$(input).off('.ClientSideValidations')After:
form.addEventListener('form:validate:before', handler)
// store and pass the handler reference to removeEventListener when unbindingThe full list of native events dispatched by ClientSideValidations: form:validate:before, form:validate:after, form:validate:pass, form:validate:fail, element:validate:before, element:validate:after, element:validate:pass, element:validate:fail.
If you are upgrading from a version older than 23.0.0, the data-csv-* renaming above is required for any custom code that still reads or writes the old attribute names. If you are already on 23.x, the new 24.x upgrade step is to update any local uniqueness integrations that still reference data-not-locally-unique or element.dataset.notLocallyUnique.
If your application vendors the compiled asset with rails g client_side_validations:copy_assets, run that generator again after upgrading so your copied asset matches the current jQuery-free bundle.
The initializer includes a commented out ActionView::Base.field_error_proc.
Uncomment this to render your error messages inline with the input fields.
I recommend you to not use a solution similar to error_messages_for. Client
Side Validations does not support this type of error rendering. If you want to
maintain consistency between the client side rendered validation error messages
and the server side rendered validation error messages please use what is in
config/initializers/client_side_validations.rb
There is additional support for other ActiveModel based ORMs and other
Rails FormBuilders. Please see the Plugin wiki page
(feel free to add your own)
In your FormBuilder you only need to enable validations:
<%= form_for @user, validate: true do |f| %>
...That should be enough to get you going.
Starting from version 14.0, ClientSideValidations also supports form_with.
The syntax is the same as form_for:
<%= form_with model: @user, validate: true do |f| %>
...Note: ClientSideValidations requires id attributes on form fields to
work, so it will force form_with to generate ids.
By default, ClientSideValidations will perform the validations in the same order specified in your models. In other words, if you want to validate the format of an email field before its presence, you can use the following:
class User < ApplicationRecord
validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/ }, presence: true
endBy default conditional validators are not evaluated and passed to the client. We do this because the state model when the form is rendered is not necessarily the state of the model when the validations fire server-side. However, if you wish to override this behavior you can do so in the form. Given the following model:
class Person < ActiveRecord::Base
validates :name, presence: true, length: { maximum: 10 }, if: :can_validate?
def can_validate?
true
end
endYou can force in the form:
<%= f.text_field :name, validate: true %>Passing validate: true will force all the validators for that attribute. If there are conditionals
they are evaluated with the state of the model when rendering the form. You can also force
individual validators:
<%= f.text_field :name, validate: { presence: true } %>In the above case only the presence validator will be passed to the client.
This is also the case with other supported conditional validations (such as Procs, Arrays or Strings).
NOTE: when :if conditional includes a symbol or a string with
changed? in it or start with will_save_change_to, validator will forced automatically.
class Person < ActiveRecord::Base
validates :name, presence: true, if: :name_changed?
endThe presence of name in the example above will be validated without explicit forcing.
This is done because it is always assumed the value will change on the form.
Conditionals defined with :unless key do not have this optimization.
If you wish to skip validations on a given attribute force it to false:
<%= f.text_field :name, validate: false %>If you want to be more selective about the validation that is turned off you can simply do:
<%= f.text_field :name, validate: { presence: false } %>You can even turn them off per fieldset:
<%= f.fields_for :profile, validate: false do |p| %>
...Please note that pass callback will also be performed on fields that skip validations.
A rendered form with validations will always have a data-client-side-validations attribute.
The objects it contains will have different keys depending upon the FormBuilder being used. However, html_settings and validators will always be present.
html_settingsThis will always contain the type to the class of the FormBuilder that did the rendering. The type will be used by the JavaScript to determine how to add and remove the error messages. If you create a new FormBuilder, you will need to write your own handlers for adding and removing.
validatorsThis object contains the validators for each of the inputs rendered on the FormBuilder. Each input is keyed to the name attribute and each containing validator could simply contain the error message itself or also specific options on how that validator should be run.
If you need to add more validators but don't want them rendered on the form immediately you can inject those validators with FormBuilder#validate:
<%= form_for @user, validate: true do |f| %>
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<%= f.validate :age, :bio %>
...In the above example age and bio will not render as inputs on the form but their validators will be properly added to the validators object for use later. If you do intend to dynamically render these inputs later the name attributes on the inputs will have to match with the keys on the validators object, and the inputs will have to be enabled for client side validation.
You can add all attributes with validators for the given object by passing nothing:
<%= f.validate %>You
No open issues yet, or sync has not completed.