TextFormFied validate spacing

TextFormFied validate spacing

Problem Description:

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 – 1

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;
},
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject