Search code examples
flutterflutter-textformfield

How to set validation of max word in textformfield in flutter?


inputFormatters: [
              LengthLimitingTextInputFormatter(50),
            ],

The above code in TextFormField restricted character length not words. I want to set validation that this field only allow to adds Max 50 words in flutter.


Solution

  • You can consider the following ways.

    1. using a TextFormField with a validator.
    TextFormField(
      validator: (text) {
        if (text.split(' ').length > max_limit) {
          return 'Reached max words';
        }
        return null;
      },
    );
    
    1. Add a decoration which will show an error if the limit is crossed.
    TextField(
      controller: _text,
      decoration: InputDecoration(
        labelText: 'Enter 5 words',
        errorText: _validate ? 'You have entered more than 5 words' : null,
      ),
    );
    

    On your OnChanged() -> update the _validate variable based on your condition.