shiang / flutter-form-with-validation-BLOC

This form and validation functions are created by using the BLOC pattern with RxDart instead of using StatefulWidget
63 stars 16 forks source link

How to use BLOC pattern to validate 'Confirm Password' text field? #1

Open jonahfang opened 5 years ago

jonahfang commented 5 years ago

I am using a Stream/Observable to validate 'Password' text field like final _emailController = BehaviorSubject(); Stream get email => _emailController.stream.transform(validateEmail); where valdiateEmail is a StreamTransformer<String,String> to validate whether the password length is at least 6. I am trying to use the similar idea for 'Confirm Password' but the validate function would take two inputs: password, confirmPassword; not sure how to handle this using StreamTransformer.

boeledi commented 5 years ago

The easiest way is to use an Observable.combineLatestXXX(), combined with a stream.transform(...).doOnData(...) as follows:

Stream<bool> get registerValid => Observable.combineLatest3(
                                      email, 
                                      password, 
                                      confirmPassword, 
                                      (e, p, c) => (0 == p.compareTo(c))
                                    );

Stream<String> get confirmPassword => 
  _passwordConfirmController.stream.transform(validatePassword)
    .doOnData((String c){
      // If the password is accepted (after validation of the rules)
      // we need to ensure both password and retyped password match
      if (0 != _passwordController.value.compareTo(c)){
        // If they do not match, add an error
        _passwordConfirmController.addError("No Match");
      }
    });

I just wrote an article on BLoC Use cases which contains a full explanation on this topic. The article may be found here

Hope this will help.

aniltc-rails commented 5 years ago

hi I have multiple textfields, in this case how to use combineLatest. let's say I have 10 textfield , its dyanmically created by the user in UI.