form-validator icon indicating copy to clipboard operation
form-validator copied to clipboard

Adding new rules with custom i18n error message

Open monisnap-julien opened this issue 4 years ago • 5 comments

As far as i'm aware, there is no way to add both a new custom validation rule and localized error message associated.

It would be great if we could extend both ValidationBuilder and FormValidatorLocale derived classes (eg: LocaleEn) or rethink a bit the way to handle it to enable this feature.

For now the solution is to copy all the localized files and handle the loading according to user's language, which is not very practical.

monisnap-julien avatar Aug 11 '20 07:08 monisnap-julien

I'm thinking about using Map<String, String> for storing i18n messages rather than classes.

final localeData = <String, String>{
  'min_length': 'Must be at least {min} characters',
};

FormValidator.addLocale('en', localeData);

addLocale will merge new locale data with previous data, so you can append custom validation messages too.

FormValidator.addLocale('en', {
  'custom_validation': 'lorem ipsum dolor ...',
});

What do you think about that?

Some other methods would be added too, for example addMessage to add single message in multiple languages:

FormValidator.addMessage('custom_validation', {
  'en': '...',
  'fr': '...',
  ...
});

themisir avatar Aug 11 '20 21:08 themisir

I think it would be a great solution for this problem 👍

monisnap-julien avatar Aug 12 '20 07:08 monisnap-julien

Fixed in v0.1.6-next. I published as prerelease since there's some breaking changes.

themisir avatar Aug 20 '20 21:08 themisir

Hello ! I've just tried this new version but i'm getting this error :

Unsupported operation: Cannot set value in unmodifiable Map

When the exception was thrown, this was the stack
#0      _ImmutableMap.[]=                              (dart:core-patch/immutable_map.dart:74:5)
#1      LocalizationImpl.addMessage             package:form_validator/src/localization_impl.dart:25

I couldn't found where this come from but maybe the Localdata is only accessible via "get" only somewhere.

monisnap-julien avatar Oct 22 '20 17:10 monisnap-julien

Hello ! I've just tried this new version but i'm getting this error :

Unsupported operation: Cannot set value in unmodifiable Map

When the exception was thrown, this was the stack
#0      _ImmutableMap.[]=                              (dart:core-patch/immutable_map.dart:74:5)
#1      LocalizationImpl.addMessage             package:form_validator/src/localization_impl.dart:25

I couldn't found where this come from but maybe the Localdata is only accessible via "get" only somewhere.

Thanks for reporting. I think const <String, String>{ ... } maps become read-only maps.

themisir avatar Oct 22 '20 18:10 themisir