Search code examples
flutterdartflutter-textformfield

TextFormFied validate spacing


I have TextFormField widget with username

TextFormField(
                controller: usernameController,
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'username is empty';
                  }
                  if (value.length <= 4) {
                    return 'passord id too short, min 4 characters';
                  }
                  return null;
                },
                decoration: const InputDecoration(
                    hintText: 'username',
                    border: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.black))),
              ),

But I want to take username to database as one word. How to validate spacing TextFormField


Solution

  • You can split the string on space and count the list length.

    validator: (value) {
      if (value!.isEmpty) {
        return 'username is empty';
      }
        if (value.trim().split(" ").length > 1) { // trim for single word extra space, you can remove it if needed
        return 'cant be multi word';
      }
      if (value.length <= 4) {
        return 'passord id too short, min 4 characters';
      }
      return null;
    },