Reputation: 11
I want to validate phone number / email address to be entered by the user in a single text form field as soon as user enters the value.I have tried using various methods of validation but this is how close I have got, still returning with errors. I want the user to either enter a email address or a phone number to get an OTP on either one for logging in the app. I am attaching an image of the [ui screen][1] to show what I want to achieve. I have tried defining final global key in main.dart as:
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// _formKey and _autoValidate
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
bool _autoValidate = false;
String _name;
String _email;
String _mobile;
`````````````````````````````````````````
I want to validate inputs on my login page and it is returning with errors in the areas highlight in bold text.
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class LoginPage extends StatefulWidget {
@override
LoginPageState createState() => LoginPageState();
}
class LoginPageState extends State<LoginPage> {
**Widget _showLoginInput() {
return Padding(
padding: EdgeInsets.only(top: 20.0),
child: TextFormField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter phone number/email id',
hintText: 'Enter phone number/email id',
),
keyboardType: TextInputType.emailAddress,
validator: validateEmail,
onSaved: (String val) {
_email = val;
},
keyboardType: TextInputType.phone,
validator: validateMobile,
onSaved: (String val) {
_mobile = val;
},
));
}
String validateMobile(String value) {
// Indian Mobile number are of 10 digit only
if (value.length != 10)
return 'Mobile Number must be of 10 digit';
else
return null;
}
String validateEmail(String value) {
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);
if (!regex.hasMatch(value))
return 'Enter Valid Email';
else
return null;
}**
Widget _showOTPAction() {
return Positioned(
bottom: 0,
child: RaisedButton(
onPressed: () {},
textColor: Colors.white,
padding: const EdgeInsets.all(0.0),
child: Container(
height: 50,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Colors.blue[700],
Colors.blue,
Colors.deepPurple[700]
])),
padding: const EdgeInsets.all(15.0),
child: const Text(
'GET OTP',
style: TextStyle(fontSize: 20),
textAlign: TextAlign.center,
),
),
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
body: Stack(children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 10.0),
**child: new Form(
key: _formKey,
autovalidate: _autoValidate,**
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 180.0,
),
Padding(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
**children: <Widget>[
_showLiteTitle(),
_showAddressTitle(),
_showLoginInput(),
_showSkipAction()
],**
))
]))),
_showOTPAction(),
]));
}
}
[1]: https://i.sstatic.net/jZQIx.png
Upvotes: 0
Views: 1421
Reputation: 372
do it like this:
String validate(String value) {
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);
if (regex.hasMatch(value))
return null;
else {
if (value.length == 10)
try {
int.parse(value);
return null;
} catch(e) {
return 'Enter valid email address/phone number';
}
else
return 'Enter valid email address/phone number';
}
}
Upvotes: 0
Reputation: 352
I would say if you want to check when the user types, then add the validation on onChanged rather than on onSave.
onChanged: (v) {
_formKey.currentState.validate();
},
This is a simple validator without any regex :
validator: (value) {
if (value.isEmpty) {
return 'Please enter email';
}
if (!value.contains('@') || value.length < 5) {
return 'Enter Valid Email';
}
return null;
},
Upvotes: 1