themisir / form-validator

Simplest form validation for flutter form widgets
https://pub.dev/packages/form_validator
MIT License
78 stars 41 forks source link

Adding new rules with custom i18n error message #7

Open monisnap-julien opened 4 years ago

monisnap-julien commented 4 years ago

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.

themisir commented 4 years ago

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': '...',
  ...
});
monisnap-julien commented 4 years ago

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

themisir commented 4 years ago

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

monisnap-julien commented 4 years ago

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.

themisir commented 4 years ago

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.