rozerro
rozerro

Reputation: 7146

What is wrong with the validation of the form

For some reason validation of the form does not work - it allows empty field submitting, what's wrong?

TextFormField(
  validator: (val) {
    if (val.trim().length == 0) {
      return Lang.key(context, 'wrongDeviceName');
    } else {
      return null;
    }
  },
  onSaved: (val) =>
      _name = toBeginningOfSentenceCase(val.trim()),
  initialValue:
      id == 0 ? '' : model.byId(id, tableName).name.toString(),
  keyboardType: TextInputType.visiblePassword,
),

How can I fix it?

Upvotes: 1

Views: 46

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may declare a validateDeviceName function in the validator and implement it:

validator: validateDeviceName

And then

String validateDeviceName(String value)
{
    RegExp regex = new RegExp(r'^[A-Za-z0-9\s]*$');
    if (!regex.hasMatch(value))
        return 'Enter Valid Device Name';
    else
        return null;
}

The ^[A-Za-z0-9\s]*$ regex matches

  • ^ - start of string
  • [A-Za-z0-9\s]* - 0 or more (*) characters that are either ASCII letters (A-Za-z), digits (0-9) or whitespace (\s)
  • $ - end of string.

See the regex demo.

There are some good hints about Form Validation in Flutter here.

Upvotes: 2

Related Questions