How can I localize validation with SimpleSchema using TAPi18n


#1

How should I define the schema?

let schema = new SimpleSchema({
  name: { type: String },
  email: { type: String, regEx: SimpleSchema.RegEx.Email },
  subject: { type: String },
  message: { type: String },
});
schema.messages({
  required: 'validation.required'
});

I am stuck, I really need help.


Which one should I use aldeed/meteor-simple-schema or aldeed/simple-schema-js?
#2

Some help please. S.O.S.


#3

Make sure this happens somewhere during startup on the client:

Tracker.autorun(function() { //needs to rerun when language is changed
	SimpleSchema.messages({
		required: TAPi18n.__('schema-validation.required'),
		...
	});
});

Set up a schema-validation object in your i18n translation file with keys for every error key.


#4

Thank you very much for your reply. In the error object I get from validated-method
there is only a message for one field and I need a custom message for each error.
Is that possible? please see the screenshot from the object in the console:


#5

Note sure if this is what you are looking for, but I set my own custom validation messages this way (have not dont extensive multi-language use of this):

SimpleSchema.setDefaultMessages({
	messages: {
		en: {
			"emailExists": "Email already registered",
			"passwordMismatch": "Passwords do not match",
			"acceptTerms": "Please accept terms",
			"authError": "Error, please check credentials"
		},
	},
});

#6

Are you sure SimpleSchema supports a language entry?
I think you have to call setDefaultMessage every time the language is changed by the user.

My problem is that for the form I am validating I only get one error message instead of an array of cusom error messages.


#7

For the error messages, I suggest you use the snippet I provided. It will auto update as soon as the user changes their language preferences and allows you to put all translations (errors and otherwise) in one separate file per language.

As for showing all error messages, I suggest you look into setting up a simpleschema validation context and it’s function addInvalidKeys. You can feed it the errors details array and end up with a validation context with just those fields. context.invalidKeys() in turn will return an array of those keys.

  • context.keyErrorMessage(k.name) will allow you to get the error message for every key
  • using the name of each one of those keys will give you access to the field in the DOM for highlighting it if you wanted to.