Reputation: 149
Hey maybe someone can help me to figure out how implement proper form validation in Flutter.
So basically in InputDecoration we have
decoration: InputDecoration(
// focusedBorder: OutlineInputBorder(
// borderSide: BorderSide(color: Colors.white, width: 3.0),
// ),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red, width: 3.0),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.greenAccent, width: 3.0),
),
focusedErrorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red, width: 3.0),
),
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.white, width: 3.0),
),
labelText: 'Email',
// errorText: !_isValid ? "Invalid Email" : null,
labelStyle: TextStyle(color: Colors.white),
prefixIcon: Padding(
padding: const EdgeInsets.only(top: 10, left: 13),
child: FaIcon(
FontAwesomeIcons.at,
color: Colors.white,
size: 25,
),
),
),
So problem is that I can't understand how to set regular border on form when it is not touched , than when it's touched , on each input it has to validate input and set error if not valid. I know that on TextFormField i can pass onchange function and do the validation
onChanged: (value) {
if (value.isEmpty || !value.contains('@')) {
setState(() {
_isValid = false;
});
print('invalid');
} else {
setState(() {
_isValid = true;
});
}
with this approach I have issue, first I have to set initial value of _isValid and in this case when form is opened and not touched it's already are enabled or with error depending on initial value of _isValid.
I came from web and worked with Angular and there we have reactive forms, maybe someone explain how to achieve similar behavior in flutter?
Upvotes: -1
Views: 1338
Reputation: 196
Define your validations, using the property validator:
, and set the property
autovalidateMode: AutovalidateMode.onUserInteraction
.
Now the validation function that you have set using validator:
will be run for each user input.
Upvotes: 0
Reputation: 100
validator: (value) {
if (enter code here
value.isEmpty || !value.contains('@')) {
return "incorrect format";
}
1 create a global form key
2 warp your widget inside a Form widget
3 pass your global key to the key parameter of your Form widget
4 and use this line on button click
5 _yourFormKey.CurrentState.Validate();
Upvotes: 0