From 6f6dcc048efb955b3159ba26a93077637ab78eb2 Mon Sep 17 00:00:00 2001 From: Alejandro Santiago Date: Thu, 7 Sep 2023 12:12:26 +0100 Subject: [PATCH] fix(example): update validation to throw on empty values --- example/lib/main.dart | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index 6a3c9b5..009cc26 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -129,7 +129,7 @@ class _MyFormState extends State { labelText: 'Email', helperText: 'A valid email e.g. joe.doe@gmail.com', ), - validator: (_) => _state.email.displayError?.text(), + validator: (value) => _state.email.validator(value ?? '')?.text(), keyboardType: TextInputType.emailAddress, textInputAction: TextInputAction.next, ), @@ -143,7 +143,8 @@ class _MyFormState extends State { labelText: 'Password', errorMaxLines: 2, ), - validator: (_) => _state.password.displayError?.text(), + validator: (value) => + _state.password.validator(value ?? '')?.text(), obscureText: true, textInputAction: TextInputAction.done, ), @@ -188,7 +189,7 @@ class MyFormState with FormzMixin { List> get inputs => [email, password]; } -enum EmailValidationError { invalid } +enum EmailValidationError { invalid, empty } class Email extends FormzInput with FormzInputErrorCacheMixin { @@ -202,11 +203,17 @@ class Email extends FormzInput @override EmailValidationError? validator(String value) { - return _emailRegExp.hasMatch(value) ? null : EmailValidationError.invalid; + if (value.isEmpty) { + return EmailValidationError.empty; + } else if (!_emailRegExp.hasMatch(value)) { + return EmailValidationError.invalid; + } + + return null; } } -enum PasswordValidationError { invalid } +enum PasswordValidationError { invalid, empty } class Password extends FormzInput { const Password.pure([super.value = '']) : super.pure(); @@ -218,9 +225,13 @@ class Password extends FormzInput { @override PasswordValidationError? validator(String value) { - return _passwordRegex.hasMatch(value) - ? null - : PasswordValidationError.invalid; + if (value.isEmpty) { + return PasswordValidationError.empty; + } else if (!_passwordRegex.hasMatch(value)) { + return PasswordValidationError.invalid; + } + + return null; } } @@ -229,6 +240,8 @@ extension on EmailValidationError { switch (this) { case EmailValidationError.invalid: return 'Please ensure the email entered is valid'; + case EmailValidationError.empty: + return 'Please enter an email'; } } } @@ -238,6 +251,8 @@ extension on PasswordValidationError { switch (this) { case PasswordValidationError.invalid: return '''Password must be at least 8 characters and contain at least one letter and number'''; + case PasswordValidationError.empty: + return 'Please enter a password'; } } }