0

I'm trying to validate a form with jQuery validate but it's doesn't seem to be returning error messages in the correct language.

In my Rails app, I have:

Gemfile

gem 'jquery-validation-rails'

application.js

//= require rails-ujs
//= require turbolinks
//= require jquery
//= require bootstrap-sprockets
//= require jquery.validate
//= require jquery.validate.localization/messages_it
//= require jquery.validate.localization/messages_ja
//= require_tree .

I call the validator with:

document.addEventListener 'turbolinks:load', ->
  $("#contact-form").validate
    submitHandler: (form) ->
      form.submit()

  $('#first_name').rules 'add',
    required: true,
    maxlength: 15

  $('#last_name').rules 'add',
    required: true,
    maxlength: 15

  $('#entry_email').rules 'add',
    required: true,
    maxlength: 60

  $('#phone-number').rules 'add',
    required: true,
    digits: true

I am seeing the error messages, but they appear in Japanese even if I switch the page locale to en or it.

The language that appears is basically the last one I set in my application.js file. So if I remove //= require jquery.validate.localization/messages_ja then I get error messages in Italian.

How can I get error messages on a per-locale basis?

Any help on fixing this would be much appreciated!

Thanks in advance

DaniG2k
  • 4,772
  • 36
  • 77
  • Based on current set I18n.locale you should set it in your html . Then you save the language as a js var as well. With that js var you could use the validator the right way: https://stackoverflow.com/questions/6181886/how-to-change-jquery-validator-language-message – Simon Franzen Mar 07 '18 at 11:47
  • I added an answer with two possibilities – Simon Franzen Mar 07 '18 at 11:51

1 Answers1

1

Don't load the translations for jquery in your application.js. Do it directly in your application layout

// in your layout file you have something like this:
<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

// additionally load translations based on given params
<% if params[:locale].present? %>
  <%= javascript_include_tag "jquery.validate.localization/messages_#{params[:locale]}" %>
<% end %>

// OR loading based on I18n.locale
<%= javascript_include_tag "jquery.validate.localization/messages_#{I18n.locale}" %>
Simon Franzen
  • 2,628
  • 25
  • 34
  • This works, just had to add them also to `Rails.application.config.assets.precompile` in **assets.rb**. Thanks! – DaniG2k Mar 07 '18 at 12:53