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)
Property | Type | Description |
---|
valid * | Boolean | The value is valid or invalid |
message | String or Object | The error message |
meta | Object | Meta 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,
};
}
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ự',
},
};
}
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:
const localeButtons = Array.from(document.querySelectorAll('.setLocaleButton'));
localeButtons.forEach(function (btn) {
btn.addEventListener('click', function () {
localeButtons.forEach(function (btn) {
btn.classList.remove('active');
});
btn.classList.add('active');
const locale = btn.getAttribute('data-locale');
fv.setLocale(locale, FormValidation.locales[locale]).resetForm();
});
});
Localize error messages of a custom validator
See also