client_side_validations 3.2.8 → 4.2.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/HISTORY.md +46 -0
- data/README.md +540 -0
- data/lib/client_side_validations.rb +0 -1
- data/lib/client_side_validations/action_view.rb +4 -3
- data/lib/client_side_validations/action_view/form_builder.rb +101 -84
- data/lib/client_side_validations/action_view/form_helper.rb +99 -110
- data/lib/client_side_validations/action_view/form_tag_helper.rb +13 -9
- data/lib/client_side_validations/active_model.rb +95 -80
- data/lib/client_side_validations/active_model/absence.rb +11 -0
- data/lib/client_side_validations/active_model/acceptance.rb +7 -6
- data/lib/client_side_validations/active_model/exclusion.rb +4 -24
- data/lib/client_side_validations/active_model/format.rb +24 -23
- data/lib/client_side_validations/active_model/inclusion.rb +4 -23
- data/lib/client_side_validations/active_model/length.rb +15 -15
- data/lib/client_side_validations/active_model/numericality.rb +23 -22
- data/lib/client_side_validations/active_model/presence.rb +7 -6
- data/lib/client_side_validations/active_record.rb +2 -2
- data/lib/client_side_validations/active_record/middleware.rb +41 -39
- data/lib/client_side_validations/active_record/uniqueness.rb +24 -23
- data/lib/client_side_validations/config.rb +1 -1
- data/lib/client_side_validations/core_ext/range.rb +1 -2
- data/lib/client_side_validations/core_ext/regexp.rb +6 -4
- data/lib/client_side_validations/engine.rb +0 -1
- data/lib/client_side_validations/generators.rb +2 -3
- data/lib/client_side_validations/generators/rails_validations.rb +2 -3
- data/lib/client_side_validations/middleware.rb +17 -24
- data/lib/client_side_validations/version.rb +1 -1
- data/lib/generators/client_side_validations/copy_assets_generator.rb +7 -11
- data/lib/generators/client_side_validations/install_generator.rb +0 -2
- data/lib/generators/templates/client_side_validations/initializer.rb +1 -2
- data/vendor/assets/javascripts/rails.validations.js +26 -20
- metadata +173 -48
- data/client_side_validations.gemspec +0 -30
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA1:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 74a0ec2fee1f73f4bbb10e8384609c16914c16e9
|
4
|
+
data.tar.gz: fdc6f78dd60b02930a4bfc876e090785c21f5206
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: 2c777cc7a0190546e612e7602e5dc578d5e30172d3b0393912ad8d2e5c2d48b36d9e3a5fe9cc5979e5ad3e8dada301d0f0eab51bca923fc8d02f63e3fcef0017
|
7
|
+
data.tar.gz: 795119c15633fb66e4b6091eb3e4a29698b49791855a64488de8c687f62fb2138924f4f849c2be99ae2cd78e8055f40bc2af3663aa935a9a431ee105ad1962c7
|
data/HISTORY.md
ADDED
@@ -0,0 +1,46 @@
|
|
1
|
+
# ClientSideValidation History
|
2
|
+
|
3
|
+
## Version 4.2
|
4
|
+
|
5
|
+
* [v4.2.0](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.2.6...v4.2.0)
|
6
|
+
|
7
|
+
## Version 3.2
|
8
|
+
|
9
|
+
* [v3.2.6](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.2.5...v3.2.6)
|
10
|
+
* [v3.2.5](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.2.4...v3.2.5)
|
11
|
+
* [v3.2.4](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.2.3...v3.2.4)
|
12
|
+
* [v3.2.3](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.2.2...v3.2.3)
|
13
|
+
* [v3.2.2](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.2.1...v3.2.2)
|
14
|
+
* [v3.2.1](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.2.0...v3.2.1)
|
15
|
+
* [v3.2.0](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.1.5...v3.2.0)
|
16
|
+
|
17
|
+
## Version 3.1
|
18
|
+
|
19
|
+
* [v3.1.5](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.1.4...v3.1.5)
|
20
|
+
* [v3.1.4](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.1.3...v3.1.4)
|
21
|
+
* [v3.1.3](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.1.2...v3.1.3)
|
22
|
+
* [v3.1.2](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.1.1...v3.1.2)
|
23
|
+
* [v3.1.1](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.1.0...v3.1.1)
|
24
|
+
* [v3.1.0](https://github.com/DavyJonesLocker/client_side_validations/compare/badf88aa6a09012900e9275bb01c80f4d19482ce...v3.1.0)
|
25
|
+
|
26
|
+
## Version 3.0
|
27
|
+
|
28
|
+
* [v3.0.13](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.12...v3.0.13)
|
29
|
+
* [v3.0.12](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.11...v3.0.12)
|
30
|
+
* [v3.0.11](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.10...v3.0.11)
|
31
|
+
* [v3.0.10](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.9...v3.0.10)
|
32
|
+
* [v3.0.9](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.8...v3.0.9)
|
33
|
+
* [v3.0.8](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.7...v3.0.8)
|
34
|
+
* [v3.0.7](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.6...v3.0.7)
|
35
|
+
* [v3.0.6](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.5...v3.0.6)
|
36
|
+
* [v3.0.5](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.4...v3.0.5)
|
37
|
+
* [v3.0.4](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.3...v3.0.4)
|
38
|
+
* [v3.0.3](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.2...v3.0.3)
|
39
|
+
* [v3.0.2](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.1...v3.0.2)
|
40
|
+
* [v3.0.1](https://github.com/DavyJonesLocker/client_side_validations/compare/v3.0.0...v3.0.1)
|
41
|
+
* [v3.0.0](https://github.com/DavyJonesLocker/client_side_validations/compare/4c6262702e513f1c4c063d36ccc88c0f3071199a...v3.0.0)
|
42
|
+
|
43
|
+
## Prior to Version 3.0
|
44
|
+
|
45
|
+
This gem was a re-write of the original [ClientSideValidationsgem](https://github.com/dnclabs/client_side_validations).
|
46
|
+
Versions were not tagged.
|
data/README.md
ADDED
@@ -0,0 +1,540 @@
|
|
1
|
+
# ClientSideValidations #
|
2
|
+
|
3
|
+
[![Gem Version](https://badge.fury.io/rb/client_side_validations.svg)](http://badge.fury.io/rb/client_side_validations)
|
4
|
+
[![Build Status](https://secure.travis-ci.org/DavyJonesLocker/client_side_validations.svg?branch=master)](https://travis-ci.org/DavyJonesLocker/client_side_validations)
|
5
|
+
[![Dependency Status](https://gemnasium.com/DavyJonesLocker/client_side_validations.svg)](https://gemnasium.com/DavyJonesLocker/client_side_validations)
|
6
|
+
[![Code Climate](https://codeclimate.com/github/DavyJonesLocker/client_side_validations/badges/gpa.svg)](https://codeclimate.com/github/DavyJonesLocker/client_side_validations)
|
7
|
+
[![Coverage Status](https://coveralls.io/repos/DavyJonesLocker/client_side_validations/badge.svg?branch=master)](https://coveralls.io/r/DavyJonesLocker/client_side_validations?branch=master)
|
8
|
+
|
9
|
+
`ClientSideValidations` made easy for your Rails 4 applications!
|
10
|
+
|
11
|
+
## Project Goals ##
|
12
|
+
|
13
|
+
1. Follow the best practices for client side validations developed by [Luke Wroblewski](http://www.alistapart.com/articles/inline-validation-in-web-forms/)
|
14
|
+
2. Automatically extract and apply validation rules defined on the
|
15
|
+
server to the client.
|
16
|
+
3. In the cases where a server-side validation rule would not work on
|
17
|
+
the client (i.e. conditional callbacks like :if, :unless) then do not
|
18
|
+
attempt client side validations. Fall back to the server side
|
19
|
+
validation.
|
20
|
+
4. The client side validation error rendering should be
|
21
|
+
indistinguishable from the server side validation error rendering.
|
22
|
+
5. Wide browser compliancy.
|
23
|
+
6. Work with any ActiveModel::Validations based model
|
24
|
+
7. Validate nested fields
|
25
|
+
8. Support custom validations
|
26
|
+
9. Client side validation callbacks
|
27
|
+
10. Plugin system to support additional FormBuilders, ORMs, etc...
|
28
|
+
|
29
|
+
## Install ##
|
30
|
+
|
31
|
+
Include `ClientSideValidations` in your Gemfile
|
32
|
+
|
33
|
+
```ruby
|
34
|
+
gem 'client_side_validations'
|
35
|
+
```
|
36
|
+
|
37
|
+
Then run the install generator
|
38
|
+
|
39
|
+
```
|
40
|
+
rails g client_side_validations:install
|
41
|
+
```
|
42
|
+
|
43
|
+
This will install the initializer:
|
44
|
+
|
45
|
+
```
|
46
|
+
config/initializers/client_side_validations.rb
|
47
|
+
```
|
48
|
+
|
49
|
+
If you want to copy the asset files from the gem into your project:
|
50
|
+
|
51
|
+
```
|
52
|
+
rails g client_side_validations:copy_assets
|
53
|
+
```
|
54
|
+
|
55
|
+
## Initializer ##
|
56
|
+
|
57
|
+
The initializer includes a commented out `ActionView::Base.field_error_proc`.
|
58
|
+
Uncomment this to render your error messages inline with the input fields.
|
59
|
+
|
60
|
+
I recommend you not use a solution similar to `error_messages_for`. Client
|
61
|
+
Side Validations is never going to support rendering this type of error
|
62
|
+
rendering. If you want to maintain consistency between the client side
|
63
|
+
rendered validation error messages and the server side rendered
|
64
|
+
validation error messages please use what is in
|
65
|
+
`config/initializers/client_side_validations.rb`
|
66
|
+
|
67
|
+
## Plugins ##
|
68
|
+
|
69
|
+
There is additional support for other `ActiveModel` based ORMs and other
|
70
|
+
Rails `FormBuilders`. Please see the [Plugin wiki page](https://github.com/DavyJonesLocker/client_side_validations/wiki/Plugins)
|
71
|
+
(feel free to add your own)
|
72
|
+
|
73
|
+
* [SimpleForm](https://github.com/DockYard/client_side_validations-simple_form)
|
74
|
+
* [Formtastic](https://github.com/DockYard/client_side_validations-formtastic)
|
75
|
+
* [Mongoid](https://github.com/DockYard/client_side_validations-mongoid)
|
76
|
+
* [MongoMapper](https://github.com/DockYard/client_side_validations-mongo_mapper)
|
77
|
+
|
78
|
+
## Usage ##
|
79
|
+
|
80
|
+
The javascript file is served up in the asset pipeline. Add the
|
81
|
+
following to your `app/assets/javascripts/application.js` file.
|
82
|
+
|
83
|
+
```js
|
84
|
+
//= require rails.validations
|
85
|
+
```
|
86
|
+
|
87
|
+
In your `FormBuilder` you only need to enable validations:
|
88
|
+
|
89
|
+
```erb
|
90
|
+
<%= form_for @user, validate: true do |f| %>
|
91
|
+
...
|
92
|
+
```
|
93
|
+
|
94
|
+
That should be enough to get you going.
|
95
|
+
|
96
|
+
By default the validators will be serialized and embedded in a
|
97
|
+
`<script>` tag following the `<form>` tag. If you would like to render
|
98
|
+
that `<script>` tag elsewhere you can do this by passing a name to
|
99
|
+
`:validate`
|
100
|
+
|
101
|
+
```erb
|
102
|
+
<%= form_for @user, validate: :user_validators do |f| %>
|
103
|
+
```
|
104
|
+
|
105
|
+
The `<script`> tag is added to `content_for()` with the name you passed,
|
106
|
+
so you can simply render that anywhere you like:
|
107
|
+
|
108
|
+
```erb
|
109
|
+
<%= yield(:user_validators) %>
|
110
|
+
```
|
111
|
+
|
112
|
+
## Conditional Validators ##
|
113
|
+
|
114
|
+
By default conditional validators are not evaluated and passed to the client.
|
115
|
+
We do this because the state model when the form is rendered is not necessarily the state
|
116
|
+
of the model when the validations fire server-side. However, if you wish to override this behavior you can do so
|
117
|
+
in the form. Given the following model:
|
118
|
+
|
119
|
+
```ruby
|
120
|
+
class Person < ActiveRecord::Base
|
121
|
+
validates :name, :email, presence: true, length: { maximum: 10 }, if: :can_validate?
|
122
|
+
|
123
|
+
def can_validate
|
124
|
+
true
|
125
|
+
end
|
126
|
+
end
|
127
|
+
```
|
128
|
+
|
129
|
+
You can force in the form:
|
130
|
+
|
131
|
+
```erb
|
132
|
+
<%= f.text_field :name, validate: true %>
|
133
|
+
```
|
134
|
+
|
135
|
+
Passing `validate: true` will force all the validators for that attribute. If there are conditionals
|
136
|
+
they are evaluated with the state of the model when rendering the form. You can also force
|
137
|
+
individual validators:
|
138
|
+
|
139
|
+
```erb
|
140
|
+
<%= f.text_field :name, validate: { presence: true } %>
|
141
|
+
```
|
142
|
+
|
143
|
+
In the above case only the `presence` validator will be passed to the client.
|
144
|
+
|
145
|
+
This is also the case with Procs, or any object that responds to `#call`
|
146
|
+
|
147
|
+
### Turning off validators ###
|
148
|
+
|
149
|
+
If you wish to skip validations on a given attribute force it to `false`:
|
150
|
+
|
151
|
+
```erb
|
152
|
+
<%= f.text_field :name, validate: false %>
|
153
|
+
```
|
154
|
+
|
155
|
+
If you want to be more selective about the validation that is turned off you can simply do:
|
156
|
+
|
157
|
+
```erb
|
158
|
+
<%= f.text_field :name, validate: { presence: false } %>
|
159
|
+
```
|
160
|
+
|
161
|
+
You can even turn them off per fieldset:
|
162
|
+
|
163
|
+
```erb
|
164
|
+
<%= f.fields_for :profile, validate: false do |p| %>
|
165
|
+
...
|
166
|
+
```
|
167
|
+
|
168
|
+
## Wrapper objects and remote validations ##
|
169
|
+
|
170
|
+
For example, we have a wrapper class for the User model, UserForm, and it uses remote uniqueness validation for the `email` field.
|
171
|
+
|
172
|
+
```ruby
|
173
|
+
class UserForm
|
174
|
+
include ActiveRecord::Validations
|
175
|
+
attr_accessor :email
|
176
|
+
validates_uniqueness_of :email
|
177
|
+
end
|
178
|
+
...
|
179
|
+
<% form_for(UserForm.new) do %>
|
180
|
+
...
|
181
|
+
```
|
182
|
+
|
183
|
+
However, this won't work since middleware will try to perform validation against UserForm, and it's not persisted.
|
184
|
+
|
185
|
+
This is solved by passing `client_validations` options hash to the validator, that currently supports one key — `:class`, and setting correct name to the form object:
|
186
|
+
|
187
|
+
```ruby
|
188
|
+
class UserForm
|
189
|
+
include ActiveRecord::Validations
|
190
|
+
attr_accessor :email
|
191
|
+
validates_uniqueness_of :email, client_validations: { class:
|
192
|
+
'User' }
|
193
|
+
end
|
194
|
+
...
|
195
|
+
<% form_for(UserForm.new, as: :user) do %>
|
196
|
+
...
|
197
|
+
```
|
198
|
+
|
199
|
+
## Understanding the embedded `<script>` tag ##
|
200
|
+
|
201
|
+
A rendered form with validations will always have a `<script>` appended
|
202
|
+
directly after:
|
203
|
+
|
204
|
+
```html
|
205
|
+
<script>//<![CDATA[if(window.ClientSideValidations==undefined)window.ClientSideValidations={};if(window.ClientSideValidations.forms==undefined)window.ClientSideValidations.forms={};window.ClientSideValidations.forms['new_person'] = {"type":"ActionView::Helpers::FormBuilder","input_tag":"<div class=\"field_with_errors\"><span id=\"input_tag\" /><label for=\"\" class=\"message\"></label></div>","label_tag":"<div class=\"field_with_errors\"><label id=\"label_tag\" /></div>","validators":{"person[name]":{"inclusion":[{"message":"is not included in the list","in":["Happy"]}]}}};//]]></script>
|
206
|
+
```
|
207
|
+
|
208
|
+
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.
|
209
|
+
|
210
|
+
### `type` ###
|
211
|
+
|
212
|
+
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.
|
213
|
+
|
214
|
+
### `validators` ###
|
215
|
+
|
216
|
+
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.
|
217
|
+
|
218
|
+
### Adding validators that aren't inputs ###
|
219
|
+
|
220
|
+
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`:
|
221
|
+
|
222
|
+
```erb
|
223
|
+
<%= form_for @user, validate: true do |f| %>
|
224
|
+
<p>
|
225
|
+
<%= f.label :name %>
|
226
|
+
<%= f.text_field :name %>
|
227
|
+
</p>
|
228
|
+
<%= f.validate :age, :bio %>
|
229
|
+
...
|
230
|
+
```
|
231
|
+
|
232
|
+
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.
|
233
|
+
|
234
|
+
You can add all attributes with validators for the given object by
|
235
|
+
passing nothing:
|
236
|
+
|
237
|
+
```erb
|
238
|
+
<%= f.validate %>
|
239
|
+
```
|
240
|
+
|
241
|
+
You can also force validators similarly to the input syntax:
|
242
|
+
|
243
|
+
```erb
|
244
|
+
<%= f.validate :email, uniqueness: false %>
|
245
|
+
```
|
246
|
+
|
247
|
+
Take care when using this method. The embedded validators are
|
248
|
+
overwritten based upon the order they are rendered. So if you do
|
249
|
+
something like:
|
250
|
+
|
251
|
+
```erb
|
252
|
+
<%= f.text_field :email, validate: { uniqueness: false } %>
|
253
|
+
<%= f.validate %>
|
254
|
+
```
|
255
|
+
|
256
|
+
The `uniqueness` validator will not be turned off because the options
|
257
|
+
were overwritten by the call to `FormBuilder#validate`
|
258
|
+
|
259
|
+
|
260
|
+
## Customize Error Rendering ##
|
261
|
+
|
262
|
+
`ClientSideValidations` will use `ActiveRecord::Base.field_error_proc` to render the error messages. Other `FormBuilders` will use their own settings.
|
263
|
+
|
264
|
+
If you need to change the markup of how the errors are rendered you can modify that in `config/initializers/client_side_validations.rb`
|
265
|
+
|
266
|
+
*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:
|
267
|
+
|
268
|
+
```js
|
269
|
+
window.ClientSideValidations.formBuilders['ActionView::Helpers::FormBuilder'] = {
|
270
|
+
add: function(element, settings, message) {
|
271
|
+
// custom add code here
|
272
|
+
},
|
273
|
+
|
274
|
+
remove: function(element, settings) {
|
275
|
+
// custom remove code here
|
276
|
+
}
|
277
|
+
}
|
278
|
+
```
|
279
|
+
|
280
|
+
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.
|
281
|
+
|
282
|
+
## Custom Validators ##
|
283
|
+
|
284
|
+
### Local Validators ###
|
285
|
+
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.
|
286
|
+
|
287
|
+
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`
|
288
|
+
|
289
|
+
```ruby
|
290
|
+
class EmailValidator < ActiveModel::EachValidator
|
291
|
+
def validate_each(record, attr_name, value)
|
292
|
+
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
|
293
|
+
record.errors.add(attr_name, :email, options.merge(value: value))
|
294
|
+
end
|
295
|
+
end
|
296
|
+
end
|
297
|
+
|
298
|
+
# This allows us to assign the validator in the model
|
299
|
+
module ActiveModel::Validations::HelperMethods
|
300
|
+
def validates_email(*attr_names)
|
301
|
+
validates_with EmailValidator, _merge_attributes(attr_names)
|
302
|
+
end
|
303
|
+
end
|
304
|
+
```
|
305
|
+
|
306
|
+
Next we need to add the error message to the Rails i18n file `config/locales/en.yml`
|
307
|
+
|
308
|
+
```yaml
|
309
|
+
# config/locales/en.yml
|
310
|
+
en:
|
311
|
+
errors:
|
312
|
+
messages:
|
313
|
+
email: "Not an email address"
|
314
|
+
```
|
315
|
+
|
316
|
+
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`
|
317
|
+
|
318
|
+
```js
|
319
|
+
// The validator variable is a JSON Object
|
320
|
+
// The selector variable is a jQuery Object
|
321
|
+
window.ClientSideValidations.validators.local['email'] = function(element, options) {
|
322
|
+
// Your validator code goes in here
|
323
|
+
if (!/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test(element.val())) {
|
324
|
+
// When the value fails to pass validation you need to return the error message.
|
325
|
+
// It can be derived from validator.message
|
326
|
+
return options.message;
|
327
|
+
}
|
328
|
+
}
|
329
|
+
```
|
330
|
+
|
331
|
+
That's it! Now you can use the custom validator as you would any other validator in your model
|
332
|
+
|
333
|
+
```ruby
|
334
|
+
# app/models/person.rb
|
335
|
+
class Person < ActiveRecord::Base
|
336
|
+
validates_email :email
|
337
|
+
end
|
338
|
+
```
|
339
|
+
|
340
|
+
Client Side Validations will apply the new validator and validate your forms as needed.
|
341
|
+
|
342
|
+
### Remote Validators ###
|
343
|
+
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:
|
344
|
+
|
345
|
+
```ruby
|
346
|
+
class ZipcodeValidator < ActiveModel::EachValidator
|
347
|
+
def validate_each(record, attr_name, value)
|
348
|
+
unless ::Zipcode.where(id: value).exists?
|
349
|
+
record.errors.add(attr_name, :zipcode, options.merge(value: value))
|
350
|
+
end
|
351
|
+
end
|
352
|
+
end
|
353
|
+
|
354
|
+
# This allows us to assign the validator in the model
|
355
|
+
module ActiveModel::Validations::HelperMethods
|
356
|
+
def validates_zipcode(*attr_names)
|
357
|
+
validates_with ZipcodeValidator, _merge_attributes(attr_names)
|
358
|
+
end
|
359
|
+
end
|
360
|
+
```
|
361
|
+
|
362
|
+
Of course we still need to add the i18n message:
|
363
|
+
|
364
|
+
```yaml
|
365
|
+
en:
|
366
|
+
errors:
|
367
|
+
messages:
|
368
|
+
zipcode: "Not a valid US zip code"
|
369
|
+
```
|
370
|
+
|
371
|
+
And let's add the Javascript validator. Because this will be remote validator we need to add it to `ClientSideValidations.validators.remote`:
|
372
|
+
|
373
|
+
```js
|
374
|
+
window.ClientSideValidations.validators.remote['zipcode'] = function(element, options) {
|
375
|
+
if ($.ajax({
|
376
|
+
url: '/validators/zipcode',
|
377
|
+
data: { id: element.val() },
|
378
|
+
// async *must* be false
|
379
|
+
async: false
|
380
|
+
}).status == 404) { return options.message; }
|
381
|
+
}
|
382
|
+
```
|
383
|
+
|
384
|
+
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.
|
385
|
+
|
386
|
+
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.
|
387
|
+
|
388
|
+
Now the extra step for adding a remote validator is to add to the middleware. All ClientSideValidations middleware should inherit from `ClientSideValidations::Middleware::Base`:
|
389
|
+
|
390
|
+
```ruby
|
391
|
+
module ClientSideValidations::Middleware
|
392
|
+
class Zipcode < ClientSideValidations::Middleware::Base
|
393
|
+
def response
|
394
|
+
if ::Zipcode.where(id: request.params[:id]).exists?
|
395
|
+
self.status = 200
|
396
|
+
else
|
397
|
+
self.status = 404
|
398
|
+
end
|
399
|
+
super
|
400
|
+
end
|
401
|
+
end
|
402
|
+
end
|
403
|
+
```
|
404
|
+
|
405
|
+
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.
|
406
|
+
|
407
|
+
## Enabling, Disabling, and Resetting on the client ##
|
408
|
+
|
409
|
+
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.
|
410
|
+
|
411
|
+
### Enabling ###
|
412
|
+
|
413
|
+
If you have rendered a new form via AJAX into your page you will need to enable that form for validation:
|
414
|
+
|
415
|
+
```js
|
416
|
+
$(new_form).enableClientSideValidations();
|
417
|
+
```
|
418
|
+
|
419
|
+
You should attach this to an event that is fired when the new HTML renders.
|
420
|
+
|
421
|
+
You can use the same function if you introduce new inputs to an existing form:
|
422
|
+
|
423
|
+
```js
|
424
|
+
$(new_input).enableClientSideValidations();
|
425
|
+
```
|
426
|
+
|
427
|
+
### Disabling ###
|
428
|
+
|
429
|
+
If you wish to turn off validations entirely on a form:
|
430
|
+
|
431
|
+
```js
|
432
|
+
$(form).disableClientSideValidations();
|
433
|
+
```
|
434
|
+
|
435
|
+
### Resetting ###
|
436
|
+
|
437
|
+
You can reset the current state of the validations, clear all error messages, and reattach clean event handlers:
|
438
|
+
|
439
|
+
```js
|
440
|
+
$(form).resetClientSideValidations();
|
441
|
+
```
|
442
|
+
|
443
|
+
## Callbacks ##
|
444
|
+
|
445
|
+
`ClientSideValidations` will run callbacks based upon the state of the element or form. The following callbacks are supported:
|
446
|
+
|
447
|
+
* `ClientSideValidations.callbacks.element.after(element, eventData)`
|
448
|
+
* `ClientSideValidations.callbacks.element.before(element, eventData)`
|
449
|
+
* `ClientSideValidations.callbacks.element.fail(element, message, callback, eventData)`
|
450
|
+
* `ClientSideValidations.callbacks.element.pass(element, callback, eventData)`
|
451
|
+
* `ClientSideValidations.callbacks.form.after(form, eventData)`
|
452
|
+
* `ClientSideValidations.callbacks.form.before(form, eventData)`
|
453
|
+
* `ClientSideValidations.callbacks.form.fail(form, eventData)`
|
454
|
+
* `ClientSideValidations.callbacks.form.pass(form, eventData)`
|
455
|
+
|
456
|
+
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.
|
457
|
+
|
458
|
+
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)
|
459
|
+
|
460
|
+
All form callbacks will receive the form in a jQuery object as the first parameter and the eventData object as the second parameter.
|
461
|
+
|
462
|
+
Here is an example callback for sliding out the error message when the validation fails then sliding it back in when the validation passes:
|
463
|
+
|
464
|
+
``` javascript
|
465
|
+
// You will need to require 'jquery-ui' for this to work
|
466
|
+
window.ClientSideValidations.callbacks.element.fail = function(element, message, callback) {
|
467
|
+
callback();
|
468
|
+
if (element.data('valid') !== false) {
|
469
|
+
element.parent().find('.message').hide().show('slide', {direction: "left", easing: "easeOutBounce"}, 500);
|
470
|
+
}
|
471
|
+
}
|
472
|
+
|
473
|
+
window.ClientSideValidations.callbacks.element.pass = function(element, callback) {
|
474
|
+
// Take note how we're passing the callback to the hide()
|
475
|
+
// method so it is run after the animation is complete.
|
476
|
+
element.parent().find('.message').hide('slide', {direction: "left"}, 500, callback);
|
477
|
+
}
|
478
|
+
```
|
479
|
+
|
480
|
+
``` css
|
481
|
+
.message {
|
482
|
+
background-color: red;
|
483
|
+
border-bottom-right-radius: 5px 5px;
|
484
|
+
border-top-right-radius: 5px 5px;
|
485
|
+
padding: 2px 5px;
|
486
|
+
}
|
487
|
+
|
488
|
+
div.field_with_errors div.ui-effects-wrapper {
|
489
|
+
display: inline-block !important;
|
490
|
+
}
|
491
|
+
```
|
492
|
+
|
493
|
+
Finally uncomment the `ActionView::Base.field_error_proc` override in `config/initializers/client_side_validations.rb`
|
494
|
+
|
495
|
+
## Security ##
|
496
|
+
|
497
|
+
Client Side Validations comes with a uniqueness middleware. This can be a potential security issue, so the uniqueness validator is disabled by default. If you want to enable it, set the `disabled_validators` config variable in `config/initializers/client_side_validations.rb`:
|
498
|
+
|
499
|
+
```ruby
|
500
|
+
ClientSideValidations::Config.disabled_validators = []
|
501
|
+
```
|
502
|
+
|
503
|
+
Note that the `FormBuilder` will automatically skip building validators that are disabled.
|
504
|
+
|
505
|
+
## Authors ##
|
506
|
+
|
507
|
+
[Brian Cardarella](http://twitter.com/bcardarella)
|
508
|
+
|
509
|
+
[Geremia Taglialatela](http://twitter.com/gtagliala)
|
510
|
+
|
511
|
+
[We are very thankful for the many contributors](https://github.com/DavyJonesLocker/client_side_validations/graphs/contributors)
|
512
|
+
|
513
|
+
## Versioning ##
|
514
|
+
|
515
|
+
This gem follows [Semantic Versioning](http://semver.org)
|
516
|
+
|
517
|
+
Major and minor version numbers will follow `Rails`'s major and
|
518
|
+
minor version numbers. For example,
|
519
|
+
`client_side_validations-4.2.0` will be compatible up to
|
520
|
+
`~> rails-4.2.0`
|
521
|
+
|
522
|
+
We will maintain compatibility with one minor version back. So the 4.2.0 version of `client_side_validations`
|
523
|
+
will be compatible with `~> rails-4.1.0`. We will not drop support
|
524
|
+
to older versions if not necessary.
|
525
|
+
|
526
|
+
Only two versions minor versions will be actively maintained.
|
527
|
+
|
528
|
+
## Want to help? ##
|
529
|
+
|
530
|
+
Please do! We are always looking to improve this gem. Please see our
|
531
|
+
[Contribution Guidelines](https://github.com/DavyJonesLocker/client_side_validations/blob/master/CONTRIBUTING.md)
|
532
|
+
on how to properly submit issues and pull requests.
|
533
|
+
|
534
|
+
## Legal ##
|
535
|
+
|
536
|
+
[DockYard](http://dockyard.com), LLC © 2012-2015
|
537
|
+
|
538
|
+
[@dockyard](http://twitter.com/dockyard)
|
539
|
+
|
540
|
+
[Licensed under the MIT license](http://www.opensource.org/licenses/mit-license.php)
|