Skip to content

Instantly share code, notes, and snippets.

@De-Morgan
Created June 19, 2021 08:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save De-Morgan/7c85c63b0c72f8c242815cf1f6a36976 to your computer and use it in GitHub Desktop.
Save De-Morgan/7c85c63b0c72f8c242815cf1f6a36976 to your computer and use it in GitHub Desktop.
Form validation
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: FormValidationExample(),
));
}
class FormValidationExample extends StatelessWidget with InputValidationMixin {
final formGlobalKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Form validation example'),
),
body:
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child:Form(
key: formGlobalKey,
child: Column(
children: [
const SizedBox(height: 50),
TextFormField(
decoration: InputDecoration(
labelText: "Email"
),
validator: (email) {
if (isEmailValid(email)) return null;
else
return 'Enter a valid email address';
},
),
const SizedBox(height: 24),
TextFormField(
decoration: InputDecoration(
labelText: "Password",
),
maxLength: 6,
obscureText: true,
validator: (password) {
if (isPasswordValid(password)) return null;
else
return 'Enter a valid password';
},
),
const SizedBox(height: 50),
ElevatedButton(
onPressed: () {
if (formGlobalKey.currentState.validate()) {
formGlobalKey.currentState.save();
// use the email provided here
}
},
child: Text("Submit"))
],
),
),
));
}
}
mixin InputValidationMixin {
bool isPasswordValid(String password) => password.length == 6;
bool isEmailValid(String email) {
Pattern pattern =
r'^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = new RegExp(pattern);
return regex.hasMatch(email);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment