ruby-on-railsvalidationparsley.jsrails-i18n

Overwrite the default Parsley translation for validations in rails


I already have all my error messages in all the languages I need them in rails config locales, so how do I change the default message for parsley required (and other validators) from

This field is required

And then how to add messages for a different language?


Solution

  • easy :)

    Parsley.addMessage('en', 'required', "something else");
    Parsley.addMessage('en', 'maxlength', 'something else max is %s')
    
    Parsley.addCatalog('zh-HANS', {required: "其他的东西"}, true);
    

    this adds the new language 'zh-HANS' to the catalog, with one translation and the final paramater true says to change Parsley to that locale, so you would say false if you were just populating a bunch of different locals. The dedicated method to change to the locale is Parsley.setLocale('zh-HANS')

    Rails part

    (in case you are using rails and have a similar situation, read on.)

    regarding rails and getting the translations into the javascript, I like to use data attributes, so if the I18n.locale is zh-HANS I would add a div with some id like

    %div#parsley-translations{data:{'current-locale'=> I18n.locale, required: I18n.t('forms.errors.required'), 'maxlength'=>I18n.t('forms.errors.maxlength')}}
    

    then in the javascript

    var translationData = $('#parsley-translations').data();
    // now use AddLocale with all the keys and values from translationData for the translationData.currentLocale - Will adjust this once I have tested and got it working