Localize error messages of a custom validator

As we know, all validators provide the same message option to indicate the error message. The error messages of built-in validators are translated into different locales.
The L10n plugin is useful when we have to work in a multiple localization environment. The plugin allows us to use error messages which are defined by a given localization package.
This example demonstrates another capacity of the L10 plugin which is able to define the error messages for a custom validator.
A custom message, likes any built-in validator, accepts the input and has to return an object of three properties:
(* denotes a required parameter)
PropertyTypeDescription
valid*BooleanThe value is valid or invalid
messageString or ObjectThe error message
metaObjectMeta data that can be used when the validation completes
If we want to use the error messages in different locales, then we need to map the locale to the corresponding message. Assume that we are going to create a custom validator to check the strength of a password.
The following sample code defines the error messages in English and Vietnamese who locales are en_US and vi_VN, respectively:
const strongPassword = function () {
return {
validate: function (input) {
const value = input.value;
if (value === '') {
return {
valid: true,
};
}
// Check the password strength
if (value.length < 8) {
return {
valid: false,
message: {
en_US: 'The password must have at least 8 characters',
vi_VN: 'Mật khẩu phải có ít nhất 8 ký tự',
},
};
}
// More checks
// ...
return {
valid: true,
};
},
};
};
We don't have to declare the error message for our custom validator:
FormValidation.validators.checkPassword = strongPassword;
const fv = FormValidation.formValidation(document.getElementById('profileForm'), {
locale: 'en_US',
localization: FormValidation.locales.en_US,
fields: {
password: {
validators: {
checkPassword: {},
},
},
},
});
The example below uses the setLocale() and resetForm() methods to update the localization and reset entire form when users switch between locales:
// Query the locate button at the top
const localeButtons = Array.from(document.querySelectorAll('.setLocaleButton'));
localeButtons.forEach(function (btn) {
// Handle the `click` event
btn.addEventListener('click', function () {
// Update the active state for the selected button
localeButtons.forEach(function (btn) {
btn.classList.remove('active');
});
btn.classList.add('active');
// Get the selected locale
const locale = btn.getAttribute('data-locale');
// Update the locale
// `fv` is the FormValidation instance
// created above
fv.setLocale(locale, FormValidation.locales[locale]).resetForm();
});
});
Localize error messages of a custom validator

See also