I'm creating a form in Flutter and want the following functionality:
- If the user enters a URL, I want to ensure it is valid with a regular expression.
- If the user leaves the field blank, I do not want to return an error message.
The following Reg Exp validator performs this way when I perform these four steps:
- If I hot reload and enter a valid URL, it accepts it.
- If I change the input field to a new non-valid URL, it still accepts it.
- If I hot reload and enter an invalid URL, it does not accept it.
- If I change the URL to a valid URL, it still does not accept it.
It's as if it only runs the validator once and then any subsequent entry is not checked again. I do have a field that uses value.isEmpty as a validator and it does work as expected by checking the input each time I click my button with _formKey.currentState.save();
child: TextFormField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Related URL',
),
textInputAction: TextInputAction.next,
keyboardType: TextInputType.url,
focusNode: _relatedUrlFocusNode,
onFieldSubmitted: (_) {
FocusScope.of(context).requestFocus(_notesFocusNode);
},
//this doesn't work
validator: (String value) {
if (RegExp(r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
.hasMatch(value)) {
return 'Please enter a valid URL';
}
return null;
},
onSaved: (String value) {
relatedUrl = value;
},
),
...other fields...
ElevatedButton(
child: Text('ADD & ACTIVATE'),
onPressed: () {
if (!_formKey.currentState.validate()) {
return;
}
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Processing Data')));
_formKey.currentState.save();
},
)
How do I ensure it performs the validator each time I click submit?
