Skip to content

Commit fcec6c3

Browse files
committed
Updated README
1 parent 14fda64 commit fcec6c3

File tree

1 file changed

+255
-11
lines changed

1 file changed

+255
-11
lines changed

README.md

Lines changed: 255 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ This will install the initializer:
4444
config/initializers/client_side_validations.rb
4545
```
4646

47-
If you are using Rails 3.1+ you'll need to use:
47+
If you want to copy the asset files from the gem into your project:
4848

4949
```
5050
rails g client_side_validations:copy_assets
@@ -56,12 +56,24 @@ The initializer includes a commented out `ActionView::Base.field_error_proc`.
5656
Uncomment this to render your error messages inline with the input fields.
5757

5858
I recommend you not use a solution similar to `error_messages_for`. Client
59-
Side Validations is never going to support rendering these type of error
60-
messages. If you want to maintain consistency between the client side
59+
Side Validations is never going to support rendering this type of error
60+
rendering. If you want to maintain consistency between the client side
6161
rendered validation error messages and the server side rendered
6262
validation error messages please use what is in
6363
`config/initializers/client_side_validations.rb`
6464

65+
## Plugins ##
66+
67+
There is additional support for other `ActiveModel` based ORMs and other
68+
Rails `FormBuilders`. Please see the [Plugin wiki page](https://github.com/bcardarella/client_side_validations/wiki/Plugins)
69+
(feel free to add your own)
70+
71+
* [SimpleForm](https://github.com/DockYard/client_side_validations-simple_form)
72+
* [Formtastic](https://github.com/DockYard/client_side_validations-formtastic)
73+
* [Mongoid](https://github.com/DockYard/client_side_validations-mongoid)
74+
* [MongoMapper](https://github.com/DockYard/client_side_validations-mongo_mapper)
75+
* [Turbolinks](https://github.com/DockYard/client_side_validations-turbolinks)
76+
6577
## Usage ##
6678

6779
The javascript file is served up in the asset pipeline. Add the
@@ -129,6 +141,13 @@ If you want to be more selective about the validation that is turned off you can
129141
<%= f.text_field :name, :validate => { :presence => false } %>
130142
```
131143

144+
You can even turn them off per fieldset:
145+
146+
```erb
147+
<%= f.fields_for :profile, :validate => false do |p| %>
148+
...
149+
```
150+
132151
## Understanding the embedded `<script>` tag ##
133152

134153
A rendered form with validations will always have a `<script>` appeneded
@@ -164,16 +183,241 @@ If you need to add more validators but don't want them rendered on the form imme
164183

165184
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.
166185

167-
## Plugins ##
168186

169-
There is additional support for other `ActiveModel` based ORMs and other
170-
Rails `FormBuilders`. Please see the [Plugin wiki page](https://github.com/bcardarella/client_side_validations/wiki/Plugins)
187+
## Customize Error Rendering ##
171188

172-
* [SimpleForm](https://github.com/DockYard/client_side_validations-simple_form)
173-
* [Formtastic](https://github.com/DockYard/client_side_validations-formtastic)
174-
* [Mongoid](https://github.com/DockYard/client_side_validations-mongoid)
175-
* [MongoMapper](https://github.com/DockYard/client_side_validations-mongo_mapper)
176-
* [Turbolinks](https://github.com/DockYard/client_side_validations-turbolinks)
189+
`ClientSideValidations` will use `ActiveRecord::Base.field_error_proc` to render the error messages. Other `FormBuilders` will use their own settings.
190+
191+
If you need to change the markup of how the errors are rendered you can modify that in `config/initializers/client_side_validations.rb`
192+
193+
*Please Note* if you modify the markup will 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:
194+
195+
```js
196+
window.ClientSideValidations.formBuilders['ActionView::Helpers::FormBuilder`] = {
197+
add: function(element, settings, message) {
198+
// custom add code here
199+
},
200+
201+
remove: function(element, settings) {
202+
// custom remove code here
203+
}
204+
}
205+
```
206+
207+
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.
208+
209+
## Custom Validators ##
210+
211+
### Local Validators ###
212+
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.
213+
214+
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`
215+
216+
```ruby
217+
class EmailValidator < ActiveModel::EachValidator
218+
def validate_each(record, attr_name, value)
219+
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
220+
record.errors.add(attr_name, :email, options.merge(:value => value))
221+
end
222+
end
223+
end
224+
225+
# This allows us to assign the validator in the model
226+
module ActiveModel::Validations::HelperMethods
227+
def validates_email(*attr_names)
228+
validates_with EmailValidator, _merge_attributes(attr_names)
229+
end
230+
end
231+
```
232+
233+
Next we need to add the error message to the Rails i18n file `config/locales/en.yml`
234+
235+
```yaml
236+
# config/locales/en.yml
237+
en:
238+
errors:
239+
messages:
240+
email: "Not an email address"
241+
```
242+
243+
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`
244+
245+
```javascript
246+
// The validator variable is a JSON Object
247+
// The selector variable is a jQuery Object
248+
window.ClientSideValidations.validators.local['email'] = function(element, options) {
249+
// Your validator code goes in here
250+
if (!/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test(element.val())) {
251+
// When the value fails to pass validation you need to return the error message.
252+
// It can be derived from validator.message
253+
return options.message;
254+
}
255+
}
256+
```
257+
258+
That's it! Now you can use the custom validator as you would any other validator in your model
259+
260+
```ruby
261+
# app/models/person.rb
262+
class Person < ActiveRecord::Base
263+
validates_email :email
264+
end
265+
```
266+
267+
Client Side Validations will apply the new validator and validate your forms as needed.
268+
269+
### Remote Validators ###
270+
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:
271+
272+
```ruby
273+
class ZipcodeValidator < ActiveModel::EachValidator
274+
def validates_each(record, attr_name, value)
275+
unless ::Zipcode.where(:id => value).exists?
276+
record.errors.add(attr_name, :zipcode, options.merge(:value => value))
277+
end
278+
end
279+
end
280+
281+
# This allows us to assign the validator in the model
282+
module ActiveModel::Validations::HelperMethods
283+
def validates_zipcode(*attr_names)
284+
validates_with ZipcodeValidator, _merge_attributes(attr_names)
285+
end
286+
end
287+
```
288+
289+
Of course we still need to add the i18n message:
290+
291+
```yaml
292+
en:
293+
errors:
294+
messages:
295+
zipcode: "Not a valid US zip code"
296+
```
297+
298+
And let's add the Javascript validator. Because this will be remote validator we need to add it to `ClientSideValidations.validators.remote`:
299+
300+
```javascript
301+
window.ClientSideValidations.validators.remote['zipcode'] = function(element, options) {
302+
if ($.ajax({
303+
url: '/validators/zipcode',
304+
data: { id: element.val() },
305+
// async *must* be false
306+
async: false
307+
}).status == 404) { return options.message; }
308+
}
309+
```
310+
311+
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.
312+
313+
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.
314+
315+
Now the extra step for adding a remote validator is to add to the middleware. All ClientSideValidations middleware should inherit from `ClientSideValidations::Middleware::Base`:
316+
317+
```ruby
318+
module ClientSideValidations::Middleware
319+
class Zipcode < ClientSideValidations::Middleware::Base
320+
def response
321+
if ::Zipcode.where(:id => request.params[:id]).exists?
322+
self.status = 200
323+
else
324+
self.status = 404
325+
end
326+
super
327+
end
328+
end
329+
end
330+
```
331+
332+
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.
333+
334+
## Enabling, Disabling, and Resetting on the client ##
335+
336+
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.
337+
338+
### Enabling ###
339+
340+
If you have rendered a new form via AJAX into your page you will need to enable that form for validation:
341+
342+
```js
343+
$(new_form).enableClientSideValidations();
344+
```
345+
346+
You should attach this to an event that is fired when the new HTML renders.
347+
348+
You can use the same function if you introduce new inputs to an existing form:
349+
350+
```js
351+
$(new_input).enableClientSideValidations();
352+
```
353+
354+
### Disabling ###
355+
356+
If you wish to turn off validations entirely on a form:
357+
358+
```js
359+
$(form).disableClientSideValidations();
360+
```
361+
362+
### Resetting ###
363+
364+
You can reset the current state of the validations, clear all error messages, and reattach clean event handlers:
365+
366+
```js
367+
$(form).resetClientSideValidations();
368+
```
369+
370+
## Callbacks ##
371+
372+
`ClientSideValidations` will run callbacks based upon the state of the element or form. The following callbacks are supported:
373+
374+
* `ClientSideValidations.callbacks.element.after(element, eventData)`
375+
* `ClientSideValidations.callbacks.element.before(element, eventData)`
376+
* `ClientSideValidations.callbacks.element.fail(element, message, callback, eventData)`
377+
* `ClientSideValidations.callbacks.element.pass(element, callback, eventData)`
378+
* `ClientSideValidations.callbacks.form.after(form, eventData)`
379+
* `ClientSideValidations.callbacks.form.before(form, eventData)`
380+
* `ClientSideValidations.callbacks.form.fail(form, eventData)`
381+
* `ClientSideValidations.callbacks.form.pass(form, eventData)`
382+
383+
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.
384+
385+
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)
386+
387+
All form callbacks will receive the form in a jQuery object as the first parameter and the eventData object as the second parameter.
388+
389+
Here is an example callback for sliding out the error message when the validation fails then sliding it back in when the validation passes:
390+
391+
``` javascript
392+
// You will need to require 'jquery-ui' for this to work
393+
window.ClientSideValidations.callbacks.element.fail = function(element, message, callback) {
394+
callback();
395+
if (element.data('valid') !== false) {
396+
element.parent().find('.message').hide().show('slide', {direction: "left", easing: "easeOutBounce"}, 500);
397+
}
398+
}
399+
400+
window.ClientSideValidations.callbacks.element.pass = function(element, callback) {
401+
// Take note how we're passing the callback to the hide()
402+
// method so it is run after the animation is complete.
403+
element.parent().find('.message').hide('slide', {direction: "left"}, 500, callback);
404+
}
405+
```
406+
407+
``` css
408+
.message {
409+
background-color: red;
410+
border-bottom-right-radius: 5px 5px;
411+
border-top-right-radius: 5px 5px;
412+
padding: 2px 5px;
413+
}
414+
415+
div.field_with_errors div.ui-effects-wrapper {
416+
display: inline-block !important;
417+
}
418+
```
419+
420+
Finally uncomment the `ActionView::Base.field_error_proc` override in `config/initializers/client_side_validations.rb`
177421

178422
## Authors ##
179423

0 commit comments

Comments
 (0)