Reputation:
I am using the below code for the email field along with the email validator in flutter application, which is working fine until if the user gives the whitespace after entering the email in the textfield, which I am not able to trim using .trim()
, how should I trim the whitespace if in case the user has entered it?
String emailValidator(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 'Email format is invalid';
} else {
return null;
}
}
final email = TextFormField(
decoration: InputDecoration(
labelText: "Email",
labelStyle: TextStyle(color: Colors.black),
prefixIcon: Icon(
LineIcons.envelope,
color: Colors.black38,
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.black38),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.orange),
),
),
keyboardType: TextInputType.text,
style: TextStyle(color: Colors.black),
cursorColor: Colors.black,
controller: emailInputController,
validator: emailValidator,
);
Upvotes: 3
Views: 10991
Reputation: 24912
It can be done in two different ways.
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(regex) // your email regex here
]
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(r"\s\b|\b\s")
]
FilteringTextInputFormatter.deny()
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.deny(regex) // your regex here
]
Upvotes: 1
Reputation: 993
For Flutter 1.20.0 and highest:
TextFormField(
validator: (value),
inputFormatters: [
FilteringTextInputFormatter.deny(new RegExp(r"\s\b|\b\s"))
],
)
Upvotes: 14
Reputation: 7492
How about you prevent user input whitespace using 'inputFormatters and BlacklistingTextInputFormatter'?
TextFormField(
validator: _validateInput,
inputFormatters: [BlacklistingTextInputFormatter(
new RegExp(r"\s\b|\b\s")
)],
...
Upvotes: 6
Reputation: 2355
you should use inputFormatter
and don't allow any white space.
TextFormField(
decoration: InputDecoration(
labelText: "Email",
labelStyle: TextStyle(color: Colors.black),
prefixIcon: Icon(
LineIcons.envelope,
color: Colors.black38,
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.black38),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.orange),
),
),
keyboardType: TextInputType.text,
style: TextStyle(color: Colors.black),
cursorColor: Colors.black,
controller: emailInputController,
validator: emailValidator,
inputFormatters: [WhitelistingTextInputFormatter(RegExp(r'[a-zA-Z0-9]'))],
)
Upvotes: -1