DEV Community

Discussion on: Why use Reactive Forms in Flutter?

 
joanpablo profile image
Joan Pablo • Edited

Hello John,

Async validators executes after every Sync validator executes without validation errors. That means that if you add for example Validators.required or Validators.email to your ReactiveTextField only when those validators marks the input as valid then the Async Validator excecutes.

But I think you are right about the issue, I will release soon a new version that let you ask inside your validator if the control is "dirty" or not, so you can check if the value has changed or not and request the server in the async validator. Mean while you can implement a workaround by asking inside your async validator if the value of the FormControl is different from the value of your model.

About the Second question, yes you can create a custom validator with additional params, there are two ways of doing this:
1-) Create a function/method that receives arguments and returns a ValidatorFunction. An example of this is the Validators.mustMatch. You can check the README.md.
2-) Extend Validator class.

Creating a function/method

// controlName and matchingControlName as additional arguments
Map<String, dynamic> _mustMatch(String controlName, String matchingControlName) {
  // returns a ValidatorFunction
  return (AbstractControl control) {
    final form = control as FormGroup;

    final formControl = form.control(controlName);
    final matchingFormControl = form.control(matchingControlName);

    if (formControl.value != matchingFormControl.value) {
      matchingFormControl.addError({'mustMatch': true});

      // force messages to show up as soon as possible
      matchingFormControl.touch(); 
    } else {
      matchingFormControl.setErrors({});
    }

    return null;
  };
}

Usage

final form = fb.group({
   'password': ['', Validators.required],
   'passwordConfirmation': ['', Validators.required],
}, [_mustMatch('password', 'passwordConfirmation')]);

Extend Validator class (this is the implementation of Validators.pattern)

/// Validator that requires the control's value to match a regex pattern.
class PatternValidator extends Validator {
  final Pattern pattern;

  /// Constructs an instance of [PatternValidator].
  ///
  /// The [pattern] argument must not be null.
  PatternValidator(this.pattern) : assert(pattern != null);

  @override
  Map<String, dynamic> validate(AbstractControl control) {
    RegExp regex = new RegExp(this.pattern);
    return (control.value == null ||
            control.value == '' ||
            regex.hasMatch(control.value))
        ? null
        : {
            ValidationMessage.pattern: {
              'requiredPattern': this.pattern.toString(),
              'actualValue': control.value,
            }
          };
  }
}

Usage

final form = fb.group({
   'email': ['', PatternValidator('some pattern').validate],
});

Validators.mustMatch and Validators.pattern are already included in Reactive Forms so you don't have to implement them, the above code are just examples to get the idea.

Thread Thread
 
zacharias02 profile image
John Lester D. Necesito • Edited

Thank you so much for your help! I will look forward to the next version of your package! ❤