how to Trim whitespace in textfield of flutter?

Viewed 6991

I am using the below code for the email field along with the email validator in flutter application, which is working fine until if the user gives the whitespace after entering the email in the textfield, which I am not able to trim using .trim(), how should I trim the whitespace if in case the user has entered it?

String emailValidator(String value) {
    Pattern pattern =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regex = new RegExp(pattern);
    if (!regex.hasMatch(value)) {
      return 'Email format is invalid';
    } else {
      return null;
    }
  }

final email = TextFormField(
      decoration: InputDecoration(
        labelText: "Email",
        labelStyle: TextStyle(color: Colors.black),
        prefixIcon: Icon(
          LineIcons.envelope,
          color: Colors.black38,
        ),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.black38),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.orange),
        ),
      ),
      keyboardType: TextInputType.text,
      style: TextStyle(color: Colors.black),
      cursorColor: Colors.black,
      controller: emailInputController,
      validator: emailValidator,
    );
3 Answers

For Flutter 1.20.0 and highest:

TextFormField(
              validator: (value),
              inputFormatters: [
                FilteringTextInputFormatter.deny(new RegExp(r"\s\b|\b\s"))
              ],
)

How about you prevent user input whitespace using 'inputFormatters and BlacklistingTextInputFormatter'?

TextFormField(
                validator: _validateInput,
                inputFormatters: [BlacklistingTextInputFormatter(
                    new RegExp(r"\s\b|\b\s")
                )],
                ...

you should use inputFormatter and don't allow any white space.

TextFormField(
      decoration: InputDecoration(
        labelText: "Email",
        labelStyle: TextStyle(color: Colors.black),
        prefixIcon: Icon(
          LineIcons.envelope,
          color: Colors.black38,
        ),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.black38),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.orange),
        ),
      ),
      keyboardType: TextInputType.text,
      style: TextStyle(color: Colors.black),
      cursorColor: Colors.black,
      controller: emailInputController,
      validator: emailValidator,
      inputFormatters: [WhitelistingTextInputFormatter(RegExp(r'[a-zA-Z0-9]'))],
)
Related