You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<%= f.fields_for :profile, :validate => false do |p| %>
148
+
...
149
+
```
150
+
132
151
## Understanding the embedded `<script>` tag ##
133
152
134
153
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
164
183
165
184
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.
166
185
167
-
## Plugins ##
168
186
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)
`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:
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
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`
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 newvalidator and validate your forms as needed.
268
+
269
+
### Remote Validators ###
270
+
A good example of a remote validator would be forZipcodes. 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
All we're doing here is checking to see if the resource exists (inthis 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 return404.
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 APIforthis.
337
+
338
+
### Enabling ###
339
+
340
+
If you have rendered a newform 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 newHTML 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:
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
0 commit comments