Caleb Burb
Caleb Burb

Reputation: 31

minLength textField attribute in Flutter

I'm trying to create a password textfield and I want the user to enter at least 8 characters. I really like the way the visible maxLength character counter on textfields work when a maxlength is set, and I was wondering if there is any equivalent for a minimum length. Thanks!

Upvotes: 3

Views: 6371

Answers (1)

MαπμQμαπkγVπ.0
MαπμQμαπkγVπ.0

Reputation: 6729

You have to use TextFormField instead of TextField.

Check this SO post:

For Text Field Validation use TextFormField instead of TextField. TextFormField needs to be wrapped with Form widget (If there are two ore more textformfields you can wrap their parent widget with form widget).Form widget requires key and autovalidate boolean (it's optional but it's recommended to show message to user when they haven't validated and as soon as they validate message stops showing). We create two variables and assign it to Form.Then we need a validator in which we validate according to our requirements.(If you need to add more validations you can add multiple if conditions.).Finally on field submitted we check if user has validated the form if validated we perform our desired action else we set autovalidate variable to true to perform autovalidation.

E.g.

TextFormField(
  ...
  validator: (String value) {
    return value.length < 8 ? 'Minimum character length is 8' : null;
  }
)

Upvotes: 1

Related Questions