formz
formz copied to clipboard
A validator of type Future
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.
+1
+1
+1
@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?
Looking at the PR discussion, it seems like there will be no async validation in the future. This is a deal breaker. In most real production application, there must be a use case for async valdiation.
@Firman95 we are open to work on async validation for Formz. I'm aware that this is a valuable feature for production applications. We want to make sure that when doing so users that will only rely on synchronous validation are not hindered.
If you want this to happen drop a 👍 on the issue, stay tuned!
@alestiago Hello, any update on this? Thanks
Hi @MiniSuperDev not so far. We haven't committed to this work yet (it's a P2), but since it has a decent number of 👍 , I'm moving it to triage so we can re-prioritise this.