Home > other >  How to set validation of max word in textformfield in flutter?
How to set validation of max word in textformfield in flutter?

Time:10-16

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.

CodePudding user response:

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.

CodePudding user response:

I created a formatter for you. Add this formatter class to your file and use this

inputFormatters: [ LengthLimitingWordInputFormatter(50), ],

class LengthLimitingWordInputFormatter extends TextInputFormatter {
      final int maxWordLength;
      LengthLimitingWordInputFormatter({required this.maxWordLength});
      @override
      TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
        if (newValue.text.split(" ").length <= maxWordLength) {
          return newValue;
        } else {
          return oldValue;
        }
      }
    }

CodePudding user response:

Use inputFormatters property. The following code would limit the textFormField to 42 in length :

new TextFormField(
  inputFormatters: [
    new LengthLimitingTextInputFormatter(42),
  ],
);

I hope, it helps!

  • Related