Skip to content

Instantly share code, notes, and snippets.

@Klerith
Created March 18, 2023 14:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Klerith/3e5cd6c543056ede3a7087bd6d6accf1 to your computer and use it in GitHub Desktop.
Save Klerith/3e5cd6c543056ede3a7087bd6d6accf1 to your computer and use it in GitHub Desktop.
Flutter - Formz Inputs
import 'package:formz/formz.dart';
// Define input validation errors
enum EmailError { empty, format }
// Extend FormzInput and provide the input type and error type.
class Email extends FormzInput<String, EmailError> {
static final RegExp emailRegExp = RegExp(
r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$',
);
// Call super.pure to represent an unmodified form input.
const Email.pure() : super.pure('');
// Call super.dirty to represent a modified form input.
const Email.dirty( String value ) : super.dirty(value);
String? get errorMessage {
if ( isValid || isPure ) return null;
if ( displayError == EmailError.empty ) return 'El campo es requerido';
if ( displayError == EmailError.format ) return 'No tiene formato de correo electrónico';
return null;
}
// Override validator to handle validating a given input value.
@override
EmailError? validator(String value) {
if ( value.isEmpty || value.trim().isEmpty ) return EmailError.empty;
if ( !emailRegExp.hasMatch(value) ) return EmailError.format;
return null;
}
}
export 'email.dart';
export 'password.dart';
import 'package:formz/formz.dart';
// Define input validation errors
enum PasswordError { empty, length, format }
// Extend FormzInput and provide the input type and error type.
class Password extends FormzInput<String, PasswordError> {
static final RegExp passwordRegExp = RegExp(
r'(?:(?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$',
);
// Call super.pure to represent an unmodified form input.
const Password.pure() : super.pure('');
// Call super.dirty to represent a modified form input.
const Password.dirty( String value ) : super.dirty(value);
String? get errorMessage {
if ( isValid || isPure ) return null;
if ( displayError == PasswordError.empty ) return 'El campo es requerido';
if ( displayError == PasswordError.length ) return 'Mínimo 6 caracteres';
if ( displayError == PasswordError.format ) return 'Debe de tener Mayúscula, letras y un número';
return null;
}
// Override validator to handle validating a given input value.
@override
PasswordError? validator(String value) {
if ( value.isEmpty || value.trim().isEmpty ) return PasswordError.empty;
if ( value.length < 6 ) return PasswordError.length;
if ( !passwordRegExp.hasMatch(value) ) return PasswordError.format;
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment