Custom validations Rails 3 style. #3

konung opened this Issue Mar 15, 2011 · 6 comments

3 participants



I have validations that are done in the following way:

validates :email, :presence => true, :length => {:minimum => 5, :maximum => 50}, :email_format => true

I also have a custom validator

class EmailFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
      object.errors[attribute] << (options[:message] || "is not formatted properly. Try something like: ")

Client_side_validations - validates my field for minimum / maximum , but not :email_format , which is just handled by server-side validation on submit.

Is this intended behavior or am I missing something? I saw the custom validations wiki page, just wondering if this setup ( like in my example) is going to be supported - this would make the usage of validates_email method ( as in your example on wiki page) unnecessary it seems.


Follow the guide in the wiki for custom validators:

From looking at the code you've supplied it looks like you haven't added the validator to the Javascript file.

Also, the style that you wrote the EmailFormatValidator looks like it is from the RailsCasts episode which is not the best practice on writing a custom validator. Please follow the guide I linked to above.


Just to elaborate, in a way this is the expected behavior if you don't supply the Javascript validator. Client Side Validations will always fall back to server side validations in any cases that the validation cannot be performed on the client. In this case, the custom validator wasn't supplied so Client Side Validations ignores that validator and let's the form to submit assuming that the server knows how to handle it.


Now that I'm looking at - I understand - I made one big erroneous assumption, I thought it sends an ajax request to server to validate. I didn't realize you do all of the validations on client side, default ones just grab data from the form, but custom ones need to be duplicated in .js

I see. Thanks for the pointer.

So from this it follows it won't check for uniqness, since that would require a call to the backend?


No, Uniqueness does a server side call. That is the only validator that requires a server-side call. ClientSideValidations adds a Rack middleware to handle uniqueness validations. The call is synchronous, not asynchronous. The blocking is required for form validation. Check out the client-side-validations.js file to see the uniqueness validator.


Could you elucidate on what makes your approach more 'best practices' than the Railscast example? Are you referring to i18n best practices or...

Just curious.


You shouldn't be hardcoding your validation messages in the model. Get into the habit of using the i18n files.

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment