Search code examples
javascriptruby-on-rails-3client-side-validation

Client side validation, trim whitespace - client_side_validations gem and Ruby on Rails 3


I was trying to validate that a username has length > 2 on the client side, using the client_side_validations gem.

Serverside in my model I had a before_validation filter to strip the whitespace, but on the client side, nothing would trim the whitespace.

How can I trim the whitespace to correctly count the number of characters in a field?

"Luke Skywalker " should count "Luke Skywalker".


Solution

  • I did it the following way:

    in rails.validations.js that client_side_validations inserts, find the following part:

    var validateElement = function(element, validators) {
        element.trigger('element:validate:before');
    

    and add the following code after:

    element.val( element.val().trim() );
    

    This strips the value of the DOM element and sends it to count the letters. This has the added benefit of trimming whitespace and replacing the text directly in the field.