skip to Main Content

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'),
            )

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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,
                ),
              ),
            ],
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search