PaulHuang
PaulHuang

Reputation: 239

How to limit TextField maximum count of words

I want to make a feature like the picture, and it needs to limit the count of input value separated by space. enter image description here

I found many solutions used maxLength, but is not working in this case.

Then I tried another way like

  onChanged: (String v) {
    // if reach the maximum count
    _controller.text = v.substring(0, _text);
  },

but the input behavior became weird.

Is there a proper way to do this?

Upvotes: 1

Views: 2723

Answers (3)

Armyone
Armyone

Reputation: 1

You can extend TextInputFormatter:

class MaxWordTextInputFormater extends TextInputFormatter {
  final int maxWords;
  final ValueChanged<int>? currentLength;

  MaxWordTextInputFormater({this.maxWords = 1, this.currentLength});

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    int count = 0;
    if (newValue.text.isEmpty) {
      count = 0;
    } else {
      count = newValue.text.trim().split(RegexUtil.spaceOrNewLine).length;
    }
    if (count > maxWords) {
      return oldValue;
    }
    currentLength?.call(count);
    return newValue;
  }
}

My Git demo.

Upvotes: 3

Anirudh Bagri
Anirudh Bagri

Reputation: 2447

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.

Upvotes: 2

Lai Zong Hao
Lai Zong Hao

Reputation: 46

You can use mask_text_input_formatter, https://pub.dev/packages/mask_text_input_formatter to help you to separate the word format that you want to split

TextField(inputFormatters: [
 MaskTextInputFormatter(mask: '+# (###) ###-##-##', filter: { "#": RegExp(r'[0- 
 9]') });

])

Upvotes: 0

Related Questions