Skip to content

Instantly share code, notes, and snippets.

@iampato
Last active April 10, 2020 14:45
Show Gist options
  • Save iampato/e71cad6d7060d5691019245aa6dc921d to your computer and use it in GitHub Desktop.
Save iampato/e71cad6d7060d5691019245aa6dc921d to your computer and use it in GitHub Desktop.
Flutter Realtime textfield validation
// import the validator
class Login extends StatefulWidget {
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
TextEditingController loginEmailController = TextEditingController();
bool get isPopulated =>
loginEmailController.text.isNotEmpty;
bool isLoginButtonEnabled(LoginState state) {
return state.isFormValid && isPopulated && !state.isSubmitting;
}
void _onEmailChanged() {
_loginBloc.add(
EmailChanged(email: loginEmailController.text),
);
}
@override
void initState() {
super.initState();
_loginBloc = BlocProvider.of<LoginBloc>(context);
loginEmailController.addListener(_onEmailChanged);
}
@override
Widget build(BuildContext context) {
return child: Form(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
top: 25, left: 10, right: 10, bottom: 10),
child: TextFormField(
controller: loginEmailController,
keyboardType: TextInputType.emailAddress,
autovalidate: true,
autocorrect: false,
validator: (_){
Validators.isValidEmail(loginEmailController.text);
},
decoration: InputDecoration(
labelText: "Email address",
prefixIcon: Icon(Icons.email),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: RaisedButton(
child: Text(
"LOGIN",
style: TextStyle(
letterSpacing: 0.6,
color: Colors.white,
fontWeight: FontWeight.bold),
),
onPressed(){
}
),
),
],
),
);
}
}
class Validators {
static final RegExp _emailRegExp = RegExp(
r'^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$',
);
}
@iampato
Copy link
Author

iampato commented Apr 10, 2020

Important import the validator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment