VeryGoodOpenSource / formz

A unified form representation in Dart used at Very Good Ventures 🦄

Home Page:https://pub.dev/packages/formz

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A validator of type Future

lambasoft opened this issue · comments

Hello,

I'm trying to use Formz to validate a phonenumber using the https://pub.dev/packages/libphonenumber library.

But libphonenumber's validation function returns a Future, so I was unable to use it in the validator() function of Formz

import 'package:formz/formz.dart';
import 'package:libphonenumber/libphonenumber.dart';

enum PhoneNumberValidationError { invalid }

class PhoneNumber extends FormzInput<String, PhoneNumberValidationError> {
  const PhoneNumber.pure() : super.pure('');

  const PhoneNumber.dirty([String value = '']) : super.dirty(value);

  static final _phoneNumberRegex = RegExp(r'^[+]{1}[0-9]{1,4}[-\s\./0-9]*$');

  @override
  PhoneNumberValidationError validator(String value) {
    return PhoneNumberUtil.isValidPhoneNumber(phoneNumber: "", isoCode: 'US').then((value){
      return null;
    });
  }
}

error: A value of type 'Future<Null>' can't be returned from method 'validator' because it has a return type of 'PhoneNumberValidationError'. (return_of_invalid_type at [datoraid] lib/models/phone_number.dart:16)

Not entirely sure if this falls into the same use case, but I think this would be great too for scenarios involving asynchronous validation of fields.

@felangel any update on this? It seems to me the simplest solution would necessitate rewriting Formz to include async validation functions.

I'd propose changing the return type to FutureOr<T>? Following the previous example:

Previously

@override
  PhoneNumberValidationError validator(String value) {
    return PhoneNumberUtil.isValidPhoneNumber(phoneNumber: "", isoCode: 'US').then((value){
      return null;
    });
  }

After

@override
 FutureOr<PhoneNumberValidationError> validator(String value)  async {
    return PhoneNumberUtil.isValidPhoneNumber(phoneNumber: "", isoCode: 'US');
  }

And add validating or loading to FormzSubmissionStatus enum

+1 ! Are there any workarounds to do async validations?