Home > OS >  TextFormField validation shows no any effect for the validator used
TextFormField validation shows no any effect for the validator used

Time:06-08

Hi I am currently trying to validate a text and number field and using TextFormField widget but even though i have defined validator, it gives no any effect.

   TextFormField(
              controller: _zipcode,
              keyboardType: TextInputType.number,
              validator: (value) {
                if (value==null || value.isEmpty ) {
                  return "Enter correct value";
                } else {
                  return null;
                }
              },
              decoration: InputDecoration(
                  labelText: 'Mileage as shown in Odometer'),
            )

CodePudding user response:

Have you used the Form() and assigned a key to the form? Please share your code to check if you have the Form() correctly.

Also, check this out. https://docs.flutter.dev/cookbook/forms/validation

CodePudding user response:

Please check below code for the same with auto validation.

class _TextSubmitWidgetState extends State<TextSubmitForm> {
  // declare a GlobalKey
  final _formKey = GlobalKey<FormState>();
  // declare a variable to keep track of the input text
  String _name = '';

  void _submit() {
    // validate all the form fields
    if (_formKey.currentState!.validate()) {
      // on success, notify the parent widget
//      widget.onSubmit(_name);
    }
  }

  @override
  Widget build(BuildContext context) {
    // build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          TextFormField(
// validate after each user interaction
  autovalidateMode: AutovalidateMode.onUserInteraction,
            decoration: const InputDecoration(
              labelText: 'Enter your name',
            ),
            // use the validator to return an error string (or null) based on the input text
            validator: (text) {
              if (text == null || text.isEmpty) {
                return 'Can\'t be empty';
              }
              if (text.length < 4) {
                return 'Too short';
              }
              return null;
            },
            // update the state variable when the text changes
            onChanged: (text) => setState(() => _name = text),
          ),
          ElevatedButton(
            // only enable the button if the text is not empty
            onPressed: _name.isNotEmpty ? _submit : null,
            child: Text(
              'Submit',
              style: Theme.of(context).textTheme.headline6,
            ),
          ),
        ],
      ),
    );
  }
}
  • Related