formz icon indicating copy to clipboard operation
formz copied to clipboard

Allow override validator error

Open iamarnas opened this issue 3 years ago • 0 comments

For now, FormzInput provides error from the validator method but sometimes need to provide error from the database as firebase for example. Of course, it is possible to create separate error values in the state but I noticed that Formz is much cleaner. I have my own class like in the example below it works as expected.

abstract class FormzInput<T, E> {
  const FormzInput._({required this.value, E? error, this.isPure = true})
      : _error = error;
  const FormzInput.pure({required T value}) : this._(value: value);
  const FormzInput.dirty({required T value, E? error})
      : this._(value: value, error: error, isPure: false);

  final T value;
  final E? _error;
  final bool isPure;

  bool get isValid => error == null ;
  bool get isNotValid => !isValid;
  E? get displayError => isPure ? null : error;
  E? get error => _error ?? validator(value); // <- ignoring validator error when `_error` is not `null`.

  E? validator(T value);
  
  //... 
}

In my example dirty constructor does not request provide error from the user, it just ignores if it is null, and does not affect old user code. By creating a new form users can decide how to initialize a dirty constructor with the error or without error.

iamarnas avatar Feb 17 '22 15:02 iamarnas