{"id":14955292,"url":"https://github.com/davyjoneslocker/client_side_validations","last_synced_at":"2025-05-07T07:39:37.722Z","repository":{"id":1360719,"uuid":"1309434","full_name":"DavyJonesLocker/client_side_validations","owner":"DavyJonesLocker","description":"Client Side Validations made easy for Ruby on Rails","archived":false,"fork":false,"pushed_at":"2025-04-26T11:13:12.000Z","size":2144,"stargazers_count":2699,"open_issues_count":9,"forks_count":404,"subscribers_count":56,"default_branch":"main","last_synced_at":"2025-04-30T14:14:50.262Z","etag":null,"topics":["clientsidevalidations","rails"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DavyJonesLocker.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2011-01-30T17:15:05.000Z","updated_at":"2025-04-26T11:13:15.000Z","dependencies_parsed_at":"2023-11-26T14:29:53.982Z","dependency_job_id":"9e87c5f0-f4ce-4880-8afc-b38a879ad2f6","html_url":"https://github.com/DavyJonesLocker/client_side_validations","commit_stats":{"total_commits":1435,"total_committers":70,"mean_commits":20.5,"dds":0.4383275261324042,"last_synced_commit":"135f0a37d2628b909837b42ae8f87d3165a9d3ea"},"previous_names":["bcardarella/client_side_validations"],"tags_count":105,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DavyJonesLocker%2Fclient_side_validations","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DavyJonesLocker%2Fclient_side_validations/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DavyJonesLocker%2Fclient_side_validations/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DavyJonesLocker%2Fclient_side_validations/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DavyJonesLocker","download_url":"https://codeload.github.com/DavyJonesLocker/client_side_validations/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252835321,"owners_count":21811518,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["clientsidevalidations","rails"],"created_at":"2024-09-24T13:10:53.614Z","updated_at":"2025-05-07T07:39:37.701Z","avatar_url":"https://github.com/DavyJonesLocker.png","language":"Ruby","readme":"# ClientSideValidations #\n\n[![Gem Version](https://badge.fury.io/rb/client_side_validations.svg)](https://badge.fury.io/rb/client_side_validations)\n[![npm version](https://badge.fury.io/js/%40client-side-validations%2Fclient-side-validations.svg)](https://badge.fury.io/js/%40client-side-validations%2Fclient-side-validations)\n[![Ruby Build Status](https://github.com/DavyJonesLocker/client_side_validations/actions/workflows/ruby.yml/badge.svg)](https://github.com/DavyJonesLocker/client_side_validations/actions)\n[![JavaScript Build Status](https://github.com/DavyJonesLocker/client_side_validations/actions/workflows/javascript.yml/badge.svg)](https://github.com/DavyJonesLocker/client_side_validations/actions)\n[![Maintainability](https://api.codeclimate.com/v1/badges/9f9e8bb6edc92615f34e/maintainability)](https://codeclimate.com/github/DavyJonesLocker/client_side_validations/maintainability)\n[![Coverage Status](https://coveralls.io/repos/github/DavyJonesLocker/client_side_validations/badge.svg?branch=main)](https://coveralls.io/github/DavyJonesLocker/client_side_validations?branch=main)\n\n\n`ClientSideValidations` made easy for your Rails 6.1, 7.x, and 8.0 applications!\n\n## Project Goals ##\n\n1. Follow the best practices for client side validations developed by [Luke Wroblewski](https://alistapart.com/article/inline-validation-in-web-forms/)\n2. Automatically extract and apply validation rules defined on the\n   server to the client.\n3. In the cases where a server-side validation rule would not work on\n   the client (i.e. conditional callbacks like :if, :unless) then do not\n   attempt client side validations. Fall back to the server side\n   validation.\n4. The client side validation error rendering should be\n   indistinguishable from the server side validation error rendering.\n5. Wide browser compliancy.\n6. Work with any ActiveModel::Validations based model\n7. Validate nested fields\n8. Support custom validations\n9. Client side validation callbacks\n10. Plugin system to support additional FormBuilders, ORMs, etc...\n\n## Install ##\n\nAdd the following line to your Gemfile:\n\n```ruby\ngem 'client_side_validations'\n```\n\nThen run `bundle install`\n\nPlease run `spring stop` if you are using [Spring](https://github.com/rails/spring)\n\nNext you need to run the generator:\n\n```\nrails g client_side_validations:install\n```\n\nThis will install the initializer:\n\n```\nconfig/initializers/client_side_validations.rb\n```\n\n### JavaScript file ###\n\nInstructions depend on your technology stack.\n\nPlease note that CSV depends on jQuery \u003e= 1.12.4 (jQuery slim is fine).\n\n####  When using Webpacker ####\n\nMake sure that you are requiring jQuery.\n\nAdd the following package:\n\n```sh\nyarn add @client-side-validations/client-side-validations\n```\n\nThen add the following line to your `app/javascript/packs/application.js` pack:\n\n```js\n// If you are using `import` syntax\nimport '@client-side-validations/client-side-validations/src'\n\n// If you are using `require` syntax\nrequire('@client-side-validations/client-side-validations')\n```\n\n##### Heads-up for Turbo and Turbolinks users #####\n\nIf you are using [Turbo](https://github.com/hotwired/turbo-rails), use the\n`import` syntax and make sure that `@client-side-validations/client-side-validations/src`\nis imported **after** `@hotwired/turbo-rails`, so ClientSideValidations can properly detect\n`window.Turbo` and attach its event handlers.\n\nIf you are using [Turbolinks](https://github.com/turbolinks/turbolinks) 5.2,\nuse the `require` syntax and make sure that `@client-side-validations/client-side-validations`\nis required **after** `Turbolinks.start()`, so ClientSideValidations can properly\ndetect `window.Turbolinks` and attach its event handlers.\n\n####  When using Sprockets ####\n\nSince ClientSideValidations can also be used via webpacker, it does not require\nby default `jquery-rails` gem.\n\nMake sure that `jquery-rails` is part of your bundled gems and `application.js`,\notherwise add:\n\n```ruby\ngem 'jquery-rails', '~\u003e 4.3'\n```\n\nto your `Gemfile`, run `bundle`, and add\n\n```js\n//= require jquery\n```\n\nto your `app/assets/javascripts/application.js` file.\n\nThen, add the following to your `app/assets/javascripts/application.js` file\nafter `//= require jquery`.\n\n```js\n//= require rails.validations\n```\n\nIf you are using [Turbolinks](https://github.com/turbolinks/turbolinks),\nmake sure that `rails.validations` is required **after** `turbolinks`, so\nClientSideValidations can properly attach its event handlers.\n\nIf you need to copy the asset files from the gem into your project, run:\n\n```\nrails g client_side_validations:copy_assets\n```\n\nNote: If you run `copy_assets`, you will need to run it again each time you update this project.\n\n## Initializer ##\n\nThe initializer includes a commented out `ActionView::Base.field_error_proc`.\nUncomment this to render your error messages inline with the input fields.\n\nI recommend you to not use a solution similar to `error_messages_for`. Client\nSide Validations does not support this type of error rendering. If you want to\nmaintain consistency between the client side rendered validation error messages\nand the server side rendered validation error messages please use what is in\n`config/initializers/client_side_validations.rb`\n\n## Plugins ##\n\nThere is additional support for other `ActiveModel` based ORMs and other\nRails `FormBuilders`. Please see the [Plugin wiki page](https://github.com/DavyJonesLocker/client_side_validations/wiki/Plugins)\n(feel free to add your own)\n\n* [SimpleForm](https://github.com/DavyJonesLocker/client_side_validations-simple_form)\n* [Mongoid](https://github.com/DavyJonesLocker/client_side_validations-mongoid)\n\n## Usage ##\n\nIn your `FormBuilder` you only need to enable validations:\n\n```erb\n\u003c%= form_for @user, validate: true do |f| %\u003e\n  ...\n```\n\nThat should be enough to get you going.\n\nStarting from version 14.0, ClientSideValidations also supports `form_with`.\nThe syntax is the same as `form_for`:\n\n```erb\n\u003c%= form_with model: @user, validate: true do |f| %\u003e\n  ...\n```\n\n**Note:** ClientSideValidations requires `id` attributes on form fields to\nwork, so it will force `form_with` to generate ids.\n\n## Validators order ##\n\nBy default, ClientSideValidations will perform the validations in the same order\nspecified in your models. In other words, if you want to validate the format\nof an email field before its presence, you can use the following:\n\n```rb\nclass User \u003c ApplicationRecord\n  validates :email, format: { with: /\\A[^@\\s]+@[^@\\s]+\\z/ }, presence: true\nend\n```\n\n## Conditional Validators ##\n\nBy default conditional validators are not evaluated and passed to the client.\nWe do this because the state model when the form is rendered is not necessarily the state\nof the model when the validations fire server-side. However, if you wish to override this behavior you can do so\nin the form. Given the following model:\n\n```ruby\nclass Person \u003c ActiveRecord::Base\n  validates :name, presence: true, length: { maximum: 10 }, if: :can_validate?\n\n  def can_validate?\n    true\n  end\nend\n```\n\nYou can force in the form:\n\n```erb\n\u003c%= f.text_field :name, validate: true %\u003e\n```\n\nPassing `validate: true` will force all the validators for that attribute. If there are conditionals\nthey are evaluated with the state of the model when rendering the form. You can also force\nindividual validators:\n\n```erb\n\u003c%= f.text_field :name, validate: { presence: true } %\u003e\n```\n\nIn the above case only the `presence` validator will be passed to the client.\n\nThis is also the case with [other supported conditional validations](https://guides.rubyonrails.org/v5.2.3/active_record_validations.html#conditional-validation) (such as Procs, Arrays or Strings).\n\n**NOTE:** when `:if` conditional includes a symbol or a string with\n`changed?` in it or start with `will_save_change_to`, validator will forced automatically.\n\n```ruby\nclass Person \u003c ActiveRecord::Base\n  validates :name, presence: true, if: :name_changed?\nend\n```\n\nThe presence of name in the example above will be validated\nwithout explicit forcing.\n\nThis is done because it is always assumed the value will change on the\nform.\n\nConditionals defined with `:unless` key do not have this optimization.\n\n### Turning off validators ###\n\nIf you wish to skip validations on a given attribute force it to `false`:\n\n```erb\n\u003c%= f.text_field :name, validate: false %\u003e\n```\n\nIf you want to be more selective about the validation that is turned off you can simply do:\n\n```erb\n\u003c%= f.text_field :name, validate: { presence: false } %\u003e\n```\n\nYou can even turn them off per fieldset:\n\n```erb\n\u003c%= f.fields_for :profile, validate: false do |p| %\u003e\n  ...\n```\n\nPlease note that `pass` callback will also be performed on fields that skip validations.\n\n## Understanding the client side validations data attribute ##\n\nA rendered form with validations will always have a `data-client-side-validations` attribute.\n\nThe objects it contains will have different keys depending upon the `FormBuilder` being used. However, `html_settings` and `validators` will always be present.\n\n### `html_settings` ###\n\nThis 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.\n\n### `validators` ###\n\nThis 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.\n\n### Adding validators that aren't inputs ###\n\nIf you need to add more validators but don't want them rendered on the form immediately you can inject those validators with `FormBuilder#validate`:\n\n```erb\n\u003c%= form_for @user, validate: true do |f| %\u003e\n  \u003cp\u003e\n    \u003c%= f.label :name %\u003e\n    \u003c%= f.text_field :name %\u003e\n  \u003c/p\u003e\n  \u003c%= f.validate :age, :bio %\u003e\n...\n```\n\nIn 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.\n\nYou can add all attributes with validators for the given object by\npassing nothing:\n\n```erb\n\u003c%= f.validate %\u003e\n```\n\nYou can also force validators similarly to the input syntax:\n\n```erb\n\u003c%= f.validate :email, presence: false %\u003e\n```\n\nTake care when using this method. The embedded validators are\noverwritten based upon the order they are rendered. So if you do\nsomething like:\n\n```erb\n\u003c%= f.text_field :email, validate: { presence: false } %\u003e\n\u003c%= f.validate %\u003e\n```\n\nThe `presence` validator will not be turned off because the options\nwere overwritten by the call to `FormBuilder#validate`\n\n\n## Customize Error Rendering ##\n\n`ClientSideValidations` will use `ActiveRecord::Base.field_error_proc` to render the error messages. Other `FormBuilders` will use their own settings.\n\nIf you need to change the markup of how the errors are rendered you can modify that in `config/initializers/client_side_validations.rb`\n\n*Please Note* if you modify the markup, you will also need to modify `ClientSideValidations.formBuilders['ActionView::Helpers::FormBuilder']`'s `add` and `remove` functions. You can override the behavior by creating a new JavaScript file called `rails.validations.actionView.js` that contains the following:\n\n```js\nwindow.ClientSideValidations.formBuilders['ActionView::Helpers::FormBuilder'] = {\n  add: function($element, settings, message) {\n    // custom add code here\n  },\n\n  remove: function($element, settings) {\n    // custom remove code here\n  }\n}\n```\n\nPlease view the code in `rails.validations.js` to see how the existing `add` and `remove` functions work and how best to override for your specific use-case.\n\n## Custom Validators ##\n\n### Local Validators ###\nClient Side Validations supports the use of custom validators. The following is an example for creating a custom validator that validates the format of email addresses.\n\nLet's say you have several models that all have email fields and you are validating the format of that email address on each one. This is a common validation and could probably benefit from a custom validator. We're going to put the validator into `config/initializers/email_validator.rb`\n\n```ruby\nclass EmailValidator \u003c ActiveModel::EachValidator\n  def validate_each(record, attr_name, value)\n    unless value =~ /^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$/i\n      record.errors.add(attr_name, :email, options.merge(value: value))\n    end\n  end\nend\n\n# This allows us to assign the validator in the model\nmodule ActiveModel::Validations::HelperMethods\n  def validates_email(*attr_names)\n    validates_with EmailValidator, _merge_attributes(attr_names)\n  end\nend\n```\n\nHeads-up!: Put custom initializers in `config/initializers`, otherwise named validator helpers will not\nbe available and migrations will not work.\n\nNext we need to add the error message to the Rails i18n file `config/locales/en.yml`\n\n```yaml\n# config/locales/en.yml\nen:\n  errors:\n    messages:\n      email: \"Not an email address\"\n```\n\nFinally we need to add a client side validator. This can be done by hooking into the `ClientSideValidations.validator` object. Create a new file `app/assets/javascripts/rails.validations.customValidators.js`\n\n```js\n// The validator variable is a JSON Object\n// The selector variable is a jQuery Object\nwindow.ClientSideValidations.validators.local['email'] = function($element, options) {\n  // Your validator code goes in here\n  if (!/^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$/i.test($element.val())) {\n    // When the value fails to pass validation you need to return the error message.\n    // It can be derived from validator.message\n    return options.message;\n  }\n}\n```\n\nThat's it! Now you can use the custom validator as you would any other validator in your model\n\n```ruby\n# app/models/person.rb\nclass Person \u003c ActiveRecord::Base\n  validates_email :email\nend\n```\n\nClient Side Validations will apply the new validator and validate your forms as needed.\n\n## Enabling, Disabling, and Resetting on the client ##\n\nThere are many reasons why you might want to enable, disable, or even completely reset the bound validation events on the client. `ClientSideValidations` offers a simple API for this.\n\n### Enabling ###\n\nIf you have rendered a new form via AJAX into your page you will need to enable that form for validation:\n\n```js\n$(new_form).enableClientSideValidations();\n```\n\nYou should attach this to an event that is fired when the new HTML renders.\n\nYou can use the same function if you introduce new inputs to an existing form:\n\n```js\n$(new_input).enableClientSideValidations();\n```\n\n### Disabling ###\n\nIf you wish to turn off validations entirely on a form:\n\n```js\n$(form).disableClientSideValidations();\n```\n\n### Resetting ###\n\nYou can reset the current state of the validations, clear all error messages, and reattach clean event handlers:\n\n```js\n$(form).resetClientSideValidations();\n```\n\n## Callbacks ##\n\n`ClientSideValidations` will run callbacks based upon the state of the element or form. The following callbacks are supported:\n\n* `ClientSideValidations.callbacks.element.after($element, eventData)`\n* `ClientSideValidations.callbacks.element.before($element, eventData)`\n* `ClientSideValidations.callbacks.element.fail($element, message, callback, eventData)`\n* `ClientSideValidations.callbacks.element.pass($element, callback, eventData)`\n* `ClientSideValidations.callbacks.form.after($form, eventData)`\n* `ClientSideValidations.callbacks.form.before($form, eventData)`\n* `ClientSideValidations.callbacks.form.fail($form, eventData)`\n* `ClientSideValidations.callbacks.form.pass($form, eventData)`\n\nThe names of the callbacks should be pretty straight forward. For example, `ClientSideValidations.callbacks.form.fail` will be called if a form failed to validate. And `ClientSideValidations.callbacks.element.before` will be called before that particular element's validations are run.\n\nAll element callbacks will receive the element in a jQuery object as the first parameter and the eventData object as the second parameter. `ClientSideValidations.callbacks.element.fail()` will receive the message of the failed validation as the second parameter, the callback for adding the error fields as the third and the eventData object as the third. `ClientSideValidations.elementValidatePass()` will receive the callback for removing the error fields. The error field callbacks must be run in your custom callback in some fashion. (either after a blocking event or as a callback for another event, such as an animation)\n\nAll form callbacks will receive the form in a jQuery object as the first parameter and the eventData object as the second parameter.\n\nHere is an example callback for sliding out the error message when the validation fails then sliding it back in when the validation passes:\n\n``` javascript\n// You will need to require 'jquery-ui' for this to work\nwindow.ClientSideValidations.callbacks.element.fail = function($element, message, callback) {\n  callback()\n\n  if ($element.data('csvValid') !== false) {\n    $element.parent().find('.message').hide().show('slide', { direction: 'left', easing: 'easeOutBounce' }, 500)\n  }\n}\n\nwindow.ClientSideValidations.callbacks.element.pass = function($element, callback) {\n  // Take note how we're passing the callback to the hide()\n  // method so it is run after the animation is complete.\n  $element.parent().find('.message').hide('slide', { direction: 'left' }, 500, callback)\n}\n```\n\n``` css\n.message {\n  background-color: red;\n  border-bottom-right-radius: 5px 5px;\n  border-top-right-radius: 5px 5px;\n  padding: 2px 5px;\n}\n\ndiv.field_with_errors div.ui-effects-wrapper {\n  display: inline-block !important;\n}\n```\n\nFinally uncomment the `ActionView::Base.field_error_proc` override in `config/initializers/client_side_validations.rb`\n\n## Disable validators ##\n\nIf you want to disable some validators, set the `disabled_validators` config variable in `config/initializers/client_side_validations.rb`:\n\n```ruby\n# Example: disable the presence validator\nClientSideValidations::Config.disabled_validators = [:presence]\n```\n\nNote that the `FormBuilder` will automatically skip building validators that are disabled.\n\n## Manual validation ##\n\nBy default, ClientSideValidations will automatically validate the form.\n\nIf for some reason you would like to manually validate the form (for example you're working with a multi-step form), you can use the following approach:\n\n```js\n$input     = $('#myInputField');\n$form      = $($input[0].form);\nvalidators = $form[0].ClientSideValidations.settings.validators;\n\n// Validate a single field\n// It might not work for multiple inputs selected at once by `$input`\n$input.isValid(validators);\n\n// Validate the whole form\n$form.isValid(validators);\n```\n\nTo manually validate a single field, you may also trigger a focusout event:\n\n```js\n$('#myInputField').trigger('focusout');\n```\n\n## Authors ##\n\n[Brian Cardarella](https://twitter.com/bcardarella)\n\n[Geremia Taglialatela](https://twitter.com/gtagliala)\n\n[We are very thankful for the many contributors](https://github.com/DavyJonesLocker/client_side_validations/graphs/contributors)\n\n## Versioning ##\n\nThis gem follows [Semantic Versioning](https://semver.org)\n\n## Want to help? ##\n\nPlease do! We are always looking to improve this gem. Please see our\n[Contribution Guidelines](https://github.com/DavyJonesLocker/client_side_validations/blob/main/CONTRIBUTING.md)\non how to properly submit issues and pull requests.\n\n## Legal ##\n\n[DockYard](https://dockyard.com/), LLC \u0026copy; 2012-2024\n\n[@dockyard](https://twitter.com/dockyard)\n\n[Licensed under the MIT license](https://opensource.org/licenses/mit)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavyjoneslocker%2Fclient_side_validations","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdavyjoneslocker%2Fclient_side_validations","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavyjoneslocker%2Fclient_side_validations/lists"}