rickharrison / validate.js

Lightweight JavaScript form validation library inspired by CodeIgniter.
http://rickharrison.github.io/validate.js
Other
2.56k stars 406 forks source link

allow setMessage to accept a map of rule / message (or add a setMessages method) #163

Open PacciniBruno opened 9 years ago

PacciniBruno commented 9 years ago

The use case would be to allow for easy internationalisation: language detection and passing of messages is handled outside validate, but setMessage should allow for easy passing of locales:

For example, setMessage could be modified as follow (I can create a PR with a complete solution + tests + documentation update if the issue is considered relevant):

FormValidator.prototype.setMessage = function(rule, message) {
    var that = this;

    if (!message && typeof rule === 'object' && !!rule) {
      Object.keys(rule).forEach(function(key) {
        that.messages[key] = rule[key];
      });
    } else {
      that.messages[rule] = message;
    }

    // return this for chaining
    return this;
};

And use:

// My object containing all localised copy:
var i18n = {};

i18n.validateJs = {
  required: 'Le champ %s doit être rempli.',
  matches: 'Le champ %s n\'est pas égal au champ %s.',
  "default": 'Le champ %s a toujours sa valeur par défaut. Veuillez la changer.',
  valid_email: 'L\'adresse renseignée doit être une adresse email valide.',
};

// SetMessage:
this.validator.setMessage(i18n.validateJs)
rickharrison commented 9 years ago

Personally, I'd be interested in seeing a companion module that is a standalone function, which could take in an internationalization object and then call the right methods on validate.js to achieve the desired effect.