pax_global_header00006660000000000000000000000064122022767430014517gustar00rootroot0000000000000052 comment=03dfff597e025e164f44621846cf25d85e596ddc client_side_validations-3.2.6/000077500000000000000000000000001220227674300164065ustar00rootroot00000000000000client_side_validations-3.2.6/.gitignore000066400000000000000000000001421220227674300203730ustar00rootroot00000000000000*.gem .bundle *.lock pkg/* tags test/generators/tmp/* *.swp .*rc bundler_stubs/* binstubs/* bin/* client_side_validations-3.2.6/.travis.yml000066400000000000000000000001251220227674300205150ustar00rootroot00000000000000rvm: - 1.9.3 before_install: - gem update --system - gem install bundler --pre client_side_validations-3.2.6/CONTRIBUTING.md000066400000000000000000000024261220227674300206430ustar00rootroot00000000000000# Contribution Guidelines # ## Submitting a new issue ## If you need to open a new issue you *must* provide the following: 1. Version of ClientSideValidations 2. Version of Rails 3. Code snippet from your model of the validations 4. The form code from your template 5. The resulting HTML along with the script tag Failure to include the above mentioned requirements will result in the issue being closed. If you want to ensure that your issue gets fixed *fast* you should attempt to reproduce the issue in an isolated example application that you can share. ## Making a pull request ## If you'd like to submit a pull request please adhere to the following: 1. Your code *must* be tested. Please TDD your code! 2. No single-character variables 3. Two-spaces instead of tabs 4. Single-quotes instead of double-quotes unless you are using string interpolation or escapes. 5. General Rails/Ruby naming conventions for files and classes 6. *Do not* use Ruby 1.9 hash syntax 7. *Do not* use Ruby 1.9 stubby proc syntax Plase note that you must adhere to each of the above mentioned rules. Failure to do so will result in an immediate closing of the pull request. If you update and rebase the pull request to follow the guidelines your pull request will be re-opened and considered for inclusion. client_side_validations-3.2.6/Gemfile000066400000000000000000000003101220227674300176730ustar00rootroot00000000000000source "http://rubygems.org" # Specify your gem's dependencies in client_side_validations.gemspec gemspec if RUBY_VERSION >= '1.9.3' gem 'debugger' elsif RUBY_VERSION < '1.9' gem 'minitest' end client_side_validations-3.2.6/HISTORY.md000066400000000000000000000044411220227674300200740ustar00rootroot00000000000000# ClientSideValidation History # ## Version 3.2 ## * [v3.2.1](https://github.com/bcardarella/client_side_validations/compare/v3.2.0...v3.2.1) * [v3.2.0](https://github.com/bcardarella/client_side_validations/compare/v3.1.5...v3.2.0) ## Version 3.1 * [v3.1.5](https://github.com/bcardarella/client_side_validations/compare/v3.1.4...v3.1.5) * [v3.1.4](https://github.com/bcardarella/client_side_validations/compare/v3.1.3...v3.1.4) * [v3.1.3](https://github.com/bcardarella/client_side_validations/compare/v3.1.2...v3.1.3) * [v3.1.2](https://github.com/bcardarella/client_side_validations/compare/v3.1.1...v3.1.2) * [v3.1.1](https://github.com/bcardarella/client_side_validations/compare/v3.1.0...v3.1.1) * [v3.1.0](https://github.com/bcardarella/client_side_validations/compare/badf88aa6a09012900e9275bb01c80f4d19482ce...v3.1.0) ## Version 3.0 * [v3.0.13](https://github.com/bcardarella/client_side_validations/compare/v3.0.12...v3.0.13) * [v3.0.12](https://github.com/bcardarella/client_side_validations/compare/v3.0.11...v3.0.12) * [v3.0.11](https://github.com/bcardarella/client_side_validations/compare/v3.0.10...v3.0.11) * [v3.0.10](https://github.com/bcardarella/client_side_validations/compare/v3.0.9...v3.0.10) * [v3.0.9](https://github.com/bcardarella/client_side_validations/compare/v3.0.8...v3.0.9) * [v3.0.8](https://github.com/bcardarella/client_side_validations/compare/v3.0.7...v3.0.8) * [v3.0.7](https://github.com/bcardarella/client_side_validations/compare/v3.0.6...v3.0.7) * [v3.0.6](https://github.com/bcardarella/client_side_validations/compare/v3.0.5...v3.0.6) * [v3.0.5](https://github.com/bcardarella/client_side_validations/compare/v3.0.4...v3.0.5) * [v3.0.4](https://github.com/bcardarella/client_side_validations/compare/v3.0.3...v3.0.4) * [v3.0.3](https://github.com/bcardarella/client_side_validations/compare/v3.0.2...v3.0.3) * [v3.0.2](https://github.com/bcardarella/client_side_validations/compare/v3.0.1...v3.0.2) * [v3.0.1](https://github.com/bcardarella/client_side_validations/compare/v3.0.0...v3.0.1) * [v3.0.0](https://github.com/bcardarella/client_side_validations/compare/4c6262702e513f1c4c063d36ccc88c0f3071199a...v3.0.0) ## Prior to Version 3.0 This gem was a re-write of the original [ClientSideValidationsgem](https://github.com/dnclabs/client_side_validations). Versions were not tagged. client_side_validations-3.2.6/README.md000066400000000000000000000474051220227674300176770ustar00rootroot00000000000000# ClientSideValidations # [![Build Status](https://secure.travis-ci.org/bcardarella/client_side_validations.png?branch=3-2-stable)](http://travis-ci.org/bcardarella/client_side_validations) [![Dependency Status](https://gemnasium.com/bcardarella/client_side_validations.png?travis)](https://gemnasium.com/bcardarella/client_side_validations) [![Code Climate](https://codeclimate.com/github/bcardarella/client_side_validations.png)](https://codeclimate.com/github/bcardarella/client_side_validations) `ClientSideValidations` made easy for your Rails v3.1+ applications! ## Project Goals ## 1. Follow the best practices for client side validations developed by [Luke Wroblewski](http://www.alistapart.com/articles/inline-validation-in-web-forms/) 2. Automatically extract and apply validation rules defined on the server to the client. 3. In the cases where a server-side validation rule would not work on the client (i.e. conditional callbacks like :if, :unless) then do not attempt client side validations. Fall back to the server side validation. 4. The client side validation error rendering should be indistinguishable from the server side validation error rendering. 5. Wide browser compliancy. 6. Work with any ActiveModel::Validations based model 7. Validate nested fields 8. Support custom validations 9. Client side validation callbacks 10. Plugin system to support additional FormBuilders, ORMs, etc... ## Install ## Include `ClientSideValidations` in your Gemfile ```ruby gem 'client_side_validations' ``` Then run the install generator ``` rails g client_side_validations:install ``` This will install the initializer: ``` config/initializers/client_side_validations.rb ``` If you want to copy the asset files from the gem into your project: ``` rails g client_side_validations:copy_assets ``` ## Initializer ## 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 not use a solution similar to `error_messages_for`. Client Side Validations is never going to support rendering 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` ## Plugins ## There is additional support for other `ActiveModel` based ORMs and other Rails `FormBuilders`. Please see the [Plugin wiki page](https://github.com/bcardarella/client_side_validations/wiki/Plugins) (feel free to add your own) * [SimpleForm](https://github.com/DockYard/client_side_validations-simple_form) * [Formtastic](https://github.com/DockYard/client_side_validations-formtastic) * [Mongoid](https://github.com/DockYard/client_side_validations-mongoid) * [MongoMapper](https://github.com/DockYard/client_side_validations-mongo_mapper) * [Turbolinks](https://github.com/DockYard/client_side_validations-turbolinks) ## Usage ## The javascript file is served up in the asset pipeline. Add the following to your `app/assets/javascripts/application.js` file. ```javascript //= require rails.validations ``` In your `FormBuilder` you only need to enable validations: ```erb <%= form_for @user, :validate => true do |f| %> ... ``` That should be enough to get you going. By default the validators will be serialized and embedded in a ` ``` This script registers a new form object on `ClientSideValidations.form`. The key is equal to the ID of the form that is rendered. The objects it contains will have different keys depending upon the `FormBuilder` being used. However, `type` and `validators` will always be present. ### `type` ### This will always be equal 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. ### `validators` ### This 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. ### Adding validators that aren't inputs ### 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`: ```erb <%= form_for @user, :validate => true do |f| %>

<%= f.label :name %> <%= f.text_field :name %>

<%= 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: ```erb <%= f.validate %> ``` You can also force validators similarly to the input syntax: ```erb <%= f.validate :email, :uniqueness => false %> ``` Take care when using this method. The embedded validators are overwritten based upon the order they are rendered. So if you do something like: ```erb <%= f.text_field :email, :validate => { :uniqueness => false } %> <%= f.validate %> ``` The `uniqueness` validator will not be turned off because the options were overwritten by the call to `FormBuilder#validate` ## Customize Error Rendering ## `ClientSideValidations` will use `ActiveRecord::Base.field_error_proc` to render the error messages. Other `FormBuilders` will use their own settings. If you need to change the markup of how the errors are rendered you can modify that in `config/initializers/client_side_validations.rb` *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: ```js window.ClientSideValidations.formBuilders['ActionView::Helpers::FormBuilder`] = { add: function(element, settings, message) { // custom add code here }, remove: function(element, settings) { // custom remove code here } } ``` Please 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. ## Custom Validators ## ### Local Validators ### Client 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. Let'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 `app/validators/email_validator.rb` ```ruby class EmailValidator < ActiveModel::EachValidator def validate_each(record, attr_name, value) unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i record.errors.add(attr_name, :email, options.merge(:value => value)) end end end # This allows us to assign the validator in the model module ActiveModel::Validations::HelperMethods def validates_email(*attr_names) validates_with EmailValidator, _merge_attributes(attr_names) end end ``` Next we need to add the error message to the Rails i18n file `config/locales/en.yml` ```yaml # config/locales/en.yml en: errors: messages: email: "Not an email address" ``` Finally 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` ```javascript // The validator variable is a JSON Object // The selector variable is a jQuery Object window.ClientSideValidations.validators.local['email'] = function(element, options) { // Your validator code goes in here if (!/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test(element.val())) { // When the value fails to pass validation you need to return the error message. // It can be derived from validator.message return options.message; } } ``` That's it! Now you can use the custom validator as you would any other validator in your model ```ruby # app/models/person.rb class Person < ActiveRecord::Base validates_email :email end ``` Client Side Validations will apply the new validator and validate your forms as needed. ### Remote Validators ### A good example of a remote validator would be for Zipcodes. It wouldn't be reasonable to embed every single zipcode inline, so we'll need to check for its existence with remote javascript call back to our app. Assume we have a zipcode database mapped to the model Zipcode. The primary key is the unique zipcode. Our Rails validator would probably look something like this: ```ruby class ZipcodeValidator < ActiveModel::EachValidator def validate_each(record, attr_name, value) unless ::Zipcode.where(:id => value).exists? record.errors.add(attr_name, :zipcode, options.merge(:value => value)) end end end # This allows us to assign the validator in the model module ActiveModel::Validations::HelperMethods def validates_zipcode(*attr_names) validates_with ZipcodeValidator, _merge_attributes(attr_names) end end ``` Of course we still need to add the i18n message: ```yaml en: errors: messages: zipcode: "Not a valid US zip code" ``` And let's add the Javascript validator. Because this will be remote validator we need to add it to `ClientSideValidations.validators.remote`: ```javascript window.ClientSideValidations.validators.remote['zipcode'] = function(element, options) { if ($.ajax({ url: '/validators/zipcode', data: { id: element.val() }, // async *must* be false async: false }).status == 404) { return options.message; } } ``` All we're doing here is checking to see if the resource exists (in this case the given zipcode) and if it doesn't the error message is returned. Notice that the remote call is forced to *async: false*. This is necessary and the validator may not work properly if this is left out. Now the extra step for adding a remote validator is to add to the middleware. All ClientSideValidations middleware should inherit from `ClientSideValidations::Middleware::Base`: ```ruby module ClientSideValidations::Middleware class Zipcode < ClientSideValidations::Middleware::Base def response if ::Zipcode.where(:id => request.params[:id]).exists? self.status = 200 else self.status = 404 end super end end end ``` The `#response` method is always called and it should set the status accessor. Then a call to `super` is required. In the javascript we set the 'id' in the params to the value of the zipcode input, in the middleware we check to see if this zipcode exists in our zipcode database. If it does, we return 200, if it doesn't we return 404. ## Enabling, Disabling, and Resetting on the client ## There 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. ### Enabling ### If you have rendered a new form via AJAX into your page you will need to enable that form for validation: ```js $(new_form).enableClientSideValidations(); ``` You should attach this to an event that is fired when the new HTML renders. You can use the same function if you introduce new inputs to an existing form: ```js $(new_input).enableClientSideValidations(); ``` ### Disabling ### If you wish to turn off validations entirely on a form: ```js $(form).disableClientSideValidations(); ``` ### Resetting ### You can reset the current state of the validations, clear all error messages, and reattach clean event handlers: ```js $(form).resetClientSideValidations(); ``` ## Callbacks ## `ClientSideValidations` will run callbacks based upon the state of the element or form. The following callbacks are supported: * `ClientSideValidations.callbacks.element.after(element, eventData)` * `ClientSideValidations.callbacks.element.before(element, eventData)` * `ClientSideValidations.callbacks.element.fail(element, message, callback, eventData)` * `ClientSideValidations.callbacks.element.pass(element, callback, eventData)` * `ClientSideValidations.callbacks.form.after(form, eventData)` * `ClientSideValidations.callbacks.form.before(form, eventData)` * `ClientSideValidations.callbacks.form.fail(form, eventData)` * `ClientSideValidations.callbacks.form.pass(form, eventData)` The 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. All 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) All form callbacks will receive the form in a jQuery object as the first parameter and the eventData object as the second parameter. Here is an example callback for sliding out the error message when the validation fails then sliding it back in when the validation passes: ``` javascript // You will need to require 'jquery-ui' for this to work window.ClientSideValidations.callbacks.element.fail = function(element, message, callback) { callback(); if (element.data('valid') !== false) { element.parent().find('.message').hide().show('slide', {direction: "left", easing: "easeOutBounce"}, 500); } } window.ClientSideValidations.callbacks.element.pass = function(element, callback) { // Take note how we're passing the callback to the hide() // method so it is run after the animation is complete. element.parent().find('.message').hide('slide', {direction: "left"}, 500, callback); } ``` ``` css .message { background-color: red; border-bottom-right-radius: 5px 5px; border-top-right-radius: 5px 5px; padding: 2px 5px; } div.field_with_errors div.ui-effects-wrapper { display: inline-block !important; } ``` Finally uncomment the `ActionView::Base.field_error_proc` override in `config/initializers/client_side_validations.rb` ## Security ## By default a uniqueness middleware is added. This can be a potential security issue. If you wish this middleware can be disabled. In `config/initializers/client_side_validations.rb` just uncomment: ```ruby ClientSideValidations::Config.disabled_validators = [:uniqueness] ``` This will completely disable the uniqueness validator. The `FormBuilder` will automatically skip building validators that are disabled. ## Authors ## [Brian Cardarella](http://twitter.com/bcardarella) [We are very thankful for the many contributors](https://github.com/bcardarella/client_side_validations/graphs/contributors) ## Versioning ## This gem follows [Semantic Versioning](http://semver.org) Major and minor version numbers will follow `Rails`'s major and minor version numbers. For example, `client_side_validations-3.2.0` will be compatible up to `~> rails-3.2.0` We will maintain compatibility with one minor version back. So the 3.2.0 version of `client_side_validations` will be compatible with `~> rails-3.1.0` Only two versions minor versions will be actively maintained. ## Want to help? ## Please do! We are always looking to improve this gem. Please see our [Contribution Guidelines](https://github.com/bcardarella/client_side_validations/blob/master/CONTRIBUTING.md) on how to properly submit issues and pull requests. ## Legal ## [DockYard](http://dockyard.com), LLC © 2012 [@dockyard](http://twitter.com/dockyard) [Licensed under the MIT license](http://www.opensource.org/licenses/mit-license.php) client_side_validations-3.2.6/Rakefile000066400000000000000000000047631220227674300200650ustar00rootroot00000000000000require 'bundler' require File.join(File.expand_path('..', __FILE__), 'coffeescript/processor') Bundler::GemHelper.install_tasks multitask :default => 'test:ruby' require 'rake/testtask' namespace :test do desc %(Run all tests) multitask :all => ['test:ruby', 'test:js'] desc %(Test Ruby code) Rake::TestTask.new(:ruby) do |test| test.libs << 'lib' << 'test' test.test_files = Dir.glob("#{File.dirname(__FILE__)}/test/**/test_*.rb").sort end desc %(Test Javascript code) multitask :js => ['test:server', 'test:open'] desc %(Starts the test server) task :server do system 'bundle exec ruby test/javascript/server.rb' end desc %(Starts the test server which reloads everything on each refresh) task :reloadable do exec "bundle exec shotgun test/javascript/config.ru -p #{PORT} --server thin" end task :open do url = "http://localhost:#{PORT}" puts "Opening test app at #{url} ..." sleep 3 system( *browse_cmd(url) ) end end desc %{Regenerate and commit JavaScript file} task :regenerate_javascript do regenerate_javascript end Rake::Task[:build].instance_eval { @actions.clear } task :build do regenerate_javascript perform_git_commit Bundler::GemHelper.new(Dir.pwd).build_gem end def perform_git_commit sh_with_code('git add vendor') out, code = sh_with_code('git commit -m "Regenerated JavaScript"') if code == 0 puts "Committed changes" else puts "Nothing to commit" end end def regenerate_javascript ClientSideValidations::Processor.run puts 'Regenerated JavaScript' end def sh_with_code(cmd, &block) cmd << " 2>&1" outbuf = '' Bundler.ui.debug(cmd) Dir.chdir(Dir.pwd) { outbuf = `#{cmd}` if $? == 0 block.call(outbuf) if block end } [outbuf, $?] end PORT = 4567 # Returns an array e.g.: ['open', 'http://example.com'] def browse_cmd(url) require 'rbconfig' browser = ENV['BROWSER'] || (RbConfig::CONFIG['host_os'].include?('darwin') && 'open') || (RbConfig::CONFIG['host_os'] =~ /msdos|mswin|djgpp|mingw|windows/ && 'start') || %w[xdg-open x-www-browser firefox opera mozilla netscape].find { |comm| which comm } abort('ERROR: no web browser detected') unless browser Array(browser) << url end # which('ruby') #=> /usr/bin/ruby def which cmd exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exts.each { |ext| exe = "#{path}/#{cmd}#{ext}" return exe if File.executable? exe } end return nil end client_side_validations-3.2.6/client_side_validations.gemspec000066400000000000000000000020761220227674300246370ustar00rootroot00000000000000# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "client_side_validations/version" Gem::Specification.new do |s| s.name = "client_side_validations" s.version = ClientSideValidations::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Brian Cardarella"] s.email = ["bcardarella@gmail.com"] s.homepage = "https://github.com/bcardarella/client_side_validations" s.summary = %q{Client Side Validations} s.description = %q{Client Side Validations} s.files = `git ls-files -- {lib/*,vendor/*,*.gemspec}`.split("\n") s.require_paths = ["lib"] s.add_development_dependency 'rails', '~> 3.2.0' s.add_development_dependency 'sqlite3' s.add_development_dependency 'mocha' s.add_development_dependency 'm' # For QUnit testing s.add_development_dependency 'sinatra', '~> 1.0' s.add_development_dependency 'shotgun' s.add_development_dependency 'thin' s.add_development_dependency 'json' s.add_development_dependency 'coffee-script' s.add_development_dependency 'jquery-rails' end client_side_validations-3.2.6/coffeescript/000077500000000000000000000000001220227674300210625ustar00rootroot00000000000000client_side_validations-3.2.6/coffeescript/processor.rb000066400000000000000000000014131220227674300234250ustar00rootroot00000000000000$:.unshift(File.expand_path('../../lib', __FILE__)) require 'client_side_validations/version' require 'coffee_script' require 'date' require 'erb' module ClientSideValidations class Processor def self.run write_file end def self.root_path File.expand_path('../..', __FILE__) end def self.file_name 'rails.validations' end def self.template ERB.new(File.open(File.join(root_path, 'coffeescript', "#{file_name}.coffee")).read) end def self.compiled_coffeescript CoffeeScript.compile(template.result(binding)) end def self.write_file file = File.new(File.join(root_path, "vendor/assets/javascripts/#{file_name}.js"), 'w') file << compiled_coffeescript file.close end end end client_side_validations-3.2.6/coffeescript/rails.validations.coffee000066400000000000000000000446211220227674300256700ustar00rootroot00000000000000# Rails 3 Client Side Validations - v<%= ClientSideValidations::VERSION %> # https://github.com/bcardarella/client_side_validations # # Copyright (c) <%= DateTime.now.year %> Brian Cardarella # Licensed under the MIT license # http://www.opensource.org/licenses/mit-license.php $ = jQuery $.fn.disableClientSideValidations = -> ClientSideValidations.disable(@) @ $.fn.enableClientSideValidations = -> @filter(ClientSideValidations.selectors.forms).each -> ClientSideValidations.enablers.form(@) @filter(ClientSideValidations.selectors.inputs).each -> ClientSideValidations.enablers.input(@) @ $.fn.resetClientSideValidations = -> @filter(ClientSideValidations.selectors.forms).each -> ClientSideValidations.reset(@) @ $.fn.validate = -> @filter(ClientSideValidations.selectors.forms).each -> $(@).enableClientSideValidations() @ $.fn.isValid = (validators) -> obj = $(@[0]) if obj.is('form') validateForm(obj, validators) else validateElement(obj, validatorsFor(@[0].name, validators)) validatorsFor = (name, validators) -> if captures = name.match /\[(\w+_attributes)\].*\[(\w+)\]$/ for validator_name, validator of validators if validator_name.match "\\[#{captures[1]}\\].*\\[\\]\\[#{captures[2]}\\]$" name = name.replace /\[[\da-z_]+\]\[(\w+)\]$/g, "[][$1]" validators[name] || {} validateForm = (form, validators) -> form.trigger('form:validate:before.ClientSideValidations') valid = true form.find(ClientSideValidations.selectors.validate_inputs).each -> valid = false unless $(@).isValid(validators) # we don't want the loop to break out by mistake true if valid then form.trigger('form:validate:pass.ClientSideValidations') else form.trigger('form:validate:fail.ClientSideValidations') form.trigger('form:validate:after.ClientSideValidations') valid validateElement = (element, validators) -> element.trigger('element:validate:before.ClientSideValidations') passElement = -> element.trigger('element:validate:pass.ClientSideValidations').data('valid', null) failElement = (message) -> element.trigger('element:validate:fail.ClientSideValidations', message).data('valid', false) false afterValidate = -> element.trigger('element:validate:after.ClientSideValidations').data('valid') != false executeValidators = (context) -> valid = true for kind, fn of context if validators[kind] for validator in validators[kind] if message = fn.call(context, element, validator) valid = failElement(message) break unless valid break valid # if _destroy for this input group == "1" pass with flying colours, it'll get deleted anyway.. destroyInputName = element.attr('name').replace(/\[([^\]]*?)\]$/, '[_destroy]') if $("input[name='#{destroyInputName}']").val() == "1" passElement() return afterValidate() # if the value hasn't changed since last validation, do nothing unless element.data('changed') != false return afterValidate() element.data('changed', false) local = ClientSideValidations.validators.local remote = ClientSideValidations.validators.remote if executeValidators(local) and executeValidators(remote) passElement() afterValidate() if window.ClientSideValidations == undefined window.ClientSideValidations = {} if window.ClientSideValidations.forms == undefined window.ClientSideValidations.forms = {} window.ClientSideValidations.selectors = inputs: ':input:not(button):not([type="submit"])[name]:visible:enabled' validate_inputs: ':input:enabled:visible[data-validate]' forms: 'form[data-validate]' window.ClientSideValidations.reset = (form) -> $form = $(form) ClientSideValidations.disable(form) for key of form.ClientSideValidations.settings.validators form.ClientSideValidations.removeError($form.find("[name='#{key}']")) ClientSideValidations.enablers.form(form) window.ClientSideValidations.disable = (target) -> $target = $(target) $target.off('.ClientSideValidations') if $target.is('form') ClientSideValidations.disable($target.find(':input')) else $target.removeData('valid') $target.removeData('changed') $target.filter(':input').each -> $(@).removeAttr('data-validate') window.ClientSideValidations.enablers = form: (form) -> $form = $(form) form.ClientSideValidations = settings: window.ClientSideValidations.forms[$form.attr('id')] addError: (element, message) -> ClientSideValidations.formBuilders[form.ClientSideValidations.settings.type].add(element, form.ClientSideValidations.settings, message) removeError: (element) -> ClientSideValidations.formBuilders[form.ClientSideValidations.settings.type].remove(element, form.ClientSideValidations.settings) # Set up the events for the form $form.on(event, binding) for event, binding of { 'submit.ClientSideValidations' : (eventData) -> unless $form.isValid(form.ClientSideValidations.settings.validators) eventData.preventDefault() eventData.stopImmediatePropagation() 'ajax:beforeSend.ClientSideValidations' : (eventData) -> $form.isValid(form.ClientSideValidations.settings.validators) if eventData.target == @ 'form:validate:after.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.after( $form, eventData) 'form:validate:before.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.form.before($form, eventData) 'form:validate:fail.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.fail( $form, eventData) 'form:validate:pass.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.pass( $form, eventData) } $form.find(ClientSideValidations.selectors.inputs).each -> ClientSideValidations.enablers.input(@) input: (input) -> $input = $(input) form = input.form $form = $(form) $input.filter(':not(:radio):not([id$=_confirmation])') .each -> $(@).attr('data-validate', true) .on(event, binding) for event, binding of { 'focusout.ClientSideValidations': -> $(@).isValid(form.ClientSideValidations.settings.validators) 'change.ClientSideValidations': -> $(@).data('changed', true) # Callbacks 'element:validate:after.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.element.after($(@), eventData) 'element:validate:before.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.element.before($(@), eventData) 'element:validate:fail.ClientSideValidations': (eventData, message) -> element = $(@) ClientSideValidations.callbacks.element.fail(element, message, -> form.ClientSideValidations.addError(element, message) , eventData) 'element:validate:pass.ClientSideValidations': (eventData) -> element = $(@) ClientSideValidations.callbacks.element.pass(element, -> form.ClientSideValidations.removeError(element) , eventData) } $input.filter(':checkbox').on('click.ClientSideValidations', -> $(@).isValid(form.ClientSideValidations.settings.validators) # If we don't return true here the checkbox will immediately uncheck itself. return true ) # Inputs for confirmations $input.filter('[id$=_confirmation]').each -> confirmationElement = $(@) element = $form.find("##{@id.match(/(.+)_confirmation/)[1]}:input") if element[0] $("##{confirmationElement.attr('id')}").on(event, binding) for event, binding of { 'focusout.ClientSideValidations': -> element.data('changed', true).isValid(form.ClientSideValidations.settings.validators) 'keyup.ClientSideValidations' : -> element.data('changed', true).isValid(form.ClientSideValidations.settings.validators) } window.ClientSideValidations.validators = all: -> jQuery.extend({}, ClientSideValidations.validators.local, ClientSideValidations.validators.remote) local: presence: (element, options) -> options.message if /^\s*$/.test(element.val() || '') acceptance: (element, options) -> switch element.attr('type') when 'checkbox' unless element.prop('checked') return options.message when 'text' if element.val() != (options.accept?.toString() || '1') return options.message format: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message return options.message if options.with and !options.with.test(element.val()) return options.message if options.without and options.without.test(element.val()) numericality: (element, options) -> val = jQuery.trim(element.val()) unless ClientSideValidations.patterns.numericality.test(val) return if options.allow_blank == true and @presence(element, {message: options.messages.numericality}) return options.messages.numericality val = val.replace(new RegExp("\\#{ClientSideValidations.number_format.delimiter}",'g'),"").replace(new RegExp("\\#{ClientSideValidations.number_format.separator}",'g'),".") if options.only_integer and !/^[+-]?\d+$/.test(val) return options.messages.only_integer CHECKS = greater_than: '>' greater_than_or_equal_to: '>=' equal_to: '==' less_than: '<' less_than_or_equal_to: '<=' form = $(element[0].form) # options[check] may be 0 so we must check for undefined for check, operator of CHECKS when options[check]? if !isNaN(parseFloat(options[check])) && isFinite(options[check]) check_value = options[check] else if form.find("[name*=#{options[check]}]").size() == 1 check_value = form.find("[name*=#{options[check]}]").val() else return fn = new Function("return #{val} #{operator} #{check_value}") return options.messages[check] unless fn() if options.odd and !(parseInt(val, 10) % 2) return options.messages.odd if options.even and (parseInt(val, 10) % 2) return options.messages.even length: (element, options) -> tokenizer = options.js_tokenizer || "split('')" tokenized_length = new Function('element', "return (element.val().#{tokenizer} || '').length")(element) CHECKS = is: '==' minimum: '>=' maximum: '<=' blankOptions = {} blankOptions.message = if options.is options.messages.is else if options.minimum options.messages.minimum message = @presence(element, blankOptions) if message return if options.allow_blank == true return message for check, operator of CHECKS when options[check] fn = new Function("return #{tokenized_length} #{operator} #{options[check]}") return options.messages[check] unless fn() exclusion: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message if options.in return options.message if element.val() in (option.toString() for option in options.in) if options.range lower = options.range[0] upper = options.range[1] return options.message if element.val() >= lower and element.val() <= upper inclusion: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message if options.in return if element.val() in (option.toString() for option in options.in) return options.message if options.range lower = options.range[0] upper = options.range[1] return if element.val() >= lower and element.val() <= upper return options.message confirmation: (element, options) -> if element.val() != jQuery("##{element.attr('id')}_confirmation").val() return options.message uniqueness: (element, options) -> name = element.attr('name') # only check uniqueness if we're in a nested form if /_attributes\]\[\d/.test(name) matches = name.match(/^(.+_attributes\])\[\d+\](.+)$/) name_prefix = matches[1] name_suffix = matches[2] value = element.val() if name_prefix && name_suffix form = element.closest('form') valid = true form.find(':input[name^="' + name_prefix + '"][name$="' + name_suffix + '"]').each -> if $(@).attr('name') != name if $(@).val() == value valid = false $(@).data('notLocallyUnique', true) else # items that were locally non-unique which become locally unique need to be # marked as changed, so they will get revalidated and thereby have their # error state cleared. but we should only do this once; therefore the # notLocallyUnique flag. if $(this).data('notLocallyUnique') $(this) .removeData('notLocallyUnique') .data('changed', true) if(!valid) return options.message remote: uniqueness: (element, options) -> message = ClientSideValidations.validators.local.presence(element, options) if message return if options.allow_blank == true return message data = {} data.case_sensitive = !!options.case_sensitive data.id = options.id if options.id if options.scope data.scope = {} for key, scope_value of options.scope scoped_name = element.attr('name').replace(/\[\w+\]$/, "[#{key}]") scoped_element = jQuery("[name='#{scoped_name}']") jQuery("[name='#{scoped_name}']:checkbox").each -> if @.checked scoped_element = @ if scoped_element[0] and scoped_element.val() != scope_value data.scope[key] = scoped_element.val() scoped_element.unbind("change.#{element.id}").bind "change.#{element.id}", -> element.trigger('change.ClientSideValidations') element.trigger('focusout.ClientSideValidations') else data.scope[key] = scope_value # Kind of a hack but this will isolate the resource name and attribute. # e.g. user[records_attributes][0][title] => records[title] # e.g. user[record_attributes][title] => record[title] # Server side handles classifying the resource properly if /_attributes\]/.test(element.attr('name')) name = element.attr('name').match(/\[\w+_attributes\]/g).pop().match(/\[(\w+)_attributes\]/).pop() name += /(\[\w+\])$/.exec(element.attr('name'))[1] else name = element.attr('name') # Override the name if a nested module class is passed name = options['class'] + '[' + name.split('[')[1] if options['class'] data[name] = element.val() if jQuery.ajax({ url: ClientSideValidations.remote_validators_url_for('uniqueness') data: data, async: false cache: false }).status == 200 return options.message window.ClientSideValidations.remote_validators_url_for = (validator) -> if ClientSideValidations.remote_validators_prefix? "//#{window.location.host}/#{ClientSideValidations.remote_validators_prefix}/validators/#{validator}" else "//#{window.location.host}/validators/#{validator}" window.ClientSideValidations.disableValidators = () -> return if window.ClientSideValidations.disabled_validators == undefined for validator, func of window.ClientSideValidations.validators.remote if validator in window.ClientSideValidations.disabled_validators delete window.ClientSideValidations.validators.remote[validator] window.ClientSideValidations.formBuilders = 'ActionView::Helpers::FormBuilder': add: (element, settings, message) -> form = $(element[0].form) if element.data('valid') != false and not form.find("label.message[for='#{element.attr('id')}']")[0]? inputErrorField = jQuery(settings.input_tag) labelErrorField = jQuery(settings.label_tag) label = form.find("label[for='#{element.attr('id')}']:not(.message)") element.attr('autofocus', false) if element.attr('autofocus') element.before(inputErrorField) inputErrorField.find('span#input_tag').replaceWith(element) inputErrorField.find('label.message').attr('for', element.attr('id')) labelErrorField.find('label.message').attr('for', element.attr('id')) labelErrorField.insertAfter(label) labelErrorField.find('label#label_tag').replaceWith(label) form.find("label.message[for='#{element.attr('id')}']").text(message) remove: (element, settings) -> form = $(element[0].form) errorFieldClass = jQuery(settings.input_tag).attr('class') inputErrorField = element.closest(".#{errorFieldClass.replace(" ", ".")}") label = form.find("label[for='#{element.attr('id')}']:not(.message)") labelErrorField = label.closest(".#{errorFieldClass}") if inputErrorField[0] inputErrorField.find("##{element.attr('id')}").detach() inputErrorField.replaceWith(element) label.detach() labelErrorField.replaceWith(label) window.ClientSideValidations.patterns = numericality: /^(-|\+)?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d*)?$/ window.ClientSideValidations.callbacks = element: after: (element, eventData) -> before: (element, eventData) -> fail: (element, message, addError, eventData) -> addError() pass: (element, removeError, eventData) -> removeError() form: after: (form, eventData) -> before: (form, eventData) -> fail: (form, eventData) -> pass: (form, eventData) -> # Main hook # If new forms are dynamically introduced into the DOM the .validate() method # must be invoked on that form $(-> ClientSideValidations.disableValidators() $(ClientSideValidations.selectors.forms).validate() ) client_side_validations-3.2.6/lib/000077500000000000000000000000001220227674300171545ustar00rootroot00000000000000client_side_validations-3.2.6/lib/client_side_validations.rb000066400000000000000000000007171220227674300243650ustar00rootroot00000000000000module ClientSideValidations end require 'client_side_validations/config' require 'client_side_validations/active_model' if defined?(::ActiveModel) require 'client_side_validations/active_record' if defined?(::ActiveRecord) require 'client_side_validations/action_view' if defined?(::ActionView) if defined?(::Rails) require 'client_side_validations/generators' require 'client_side_validations/middleware' require 'client_side_validations/engine' end client_side_validations-3.2.6/lib/client_side_validations/000077500000000000000000000000001220227674300240335ustar00rootroot00000000000000client_side_validations-3.2.6/lib/client_side_validations/action_view.rb000066400000000000000000000011011220227674300266600ustar00rootroot00000000000000module ClientSideValidations::ActionView module Helpers end end require 'client_side_validations/core_ext' require 'client_side_validations/action_view/form_helper' require 'client_side_validations/action_view/form_tag_helper' require 'client_side_validations/action_view/form_builder' ActionView::Base.send(:include, ClientSideValidations::ActionView::Helpers::FormHelper) ActionView::Base.send(:include, ClientSideValidations::ActionView::Helpers::FormTagHelper) ActionView::Helpers::FormBuilder.send(:include, ClientSideValidations::ActionView::Helpers::FormBuilder) client_side_validations-3.2.6/lib/client_side_validations/action_view/000077500000000000000000000000001220227674300263425ustar00rootroot00000000000000client_side_validations-3.2.6/lib/client_side_validations/action_view/form_builder.rb000066400000000000000000000122761220227674300313500ustar00rootroot00000000000000module ClientSideValidations::ActionView::Helpers module FormBuilder def self.included(base) (base.field_helpers.map(&:to_s) - %w(apply_form_for_options! label check_box radio_button fields_for hidden_field)).each do |selector| base.class_eval <<-RUBY_EVAL def #{selector}_with_client_side_validations(method, options = {}) build_validation_options(method, options) options.delete(:validate) #{selector}_without_client_side_validations(method, options) end RUBY_EVAL base.class_eval { alias_method_chain selector, :client_side_validations } end base.class_eval do alias_method_chain :initialize, :client_side_validations alias_method_chain :fields_for, :client_side_validations alias_method_chain :check_box, :client_side_validations alias_method_chain :radio_button, :client_side_validations alias_method_chain :select, :client_side_validations alias_method_chain :collection_select, :client_side_validations alias_method_chain :grouped_collection_select, :client_side_validations alias_method_chain :time_zone_select, :client_side_validations def client_side_form_settings(options, form_helper) { :type => self.class.to_s, :input_tag => form_helper.class.field_error_proc.call(%{}, Struct.new(:error_message, :tag_id).new([], "")), :label_tag => form_helper.class.field_error_proc.call(%{