Search code examples
validationfluttererror-handlingflutter-layouttrim

white space is not removing from string in flutter


I have a question about trim function. when I am using trim it's not working. when I am adding white space and then used the trim function but still my validation is true. instead of trim has to remove all white space. Hope you understand the question. thank you in advance.

 Widget _buildUserNameField() {
    return EnsureVisibleWhenFocused(
      focusNode: _emailFocusNode,
      child: TudoEmailWidget(
        focusNode: _emailFocusNode,
        prefixIcon: Icon(Icons.email),
        labelText: AppConstantsValue.appConst['login']['email']['translation'],
        validator: Validators().validateEmail,
        onSaved: (val) => _username = val.trim(),
      ),
    );
  }

Solution

  • The onSaved event is called only when you save the form (call to form.save()).

    If you want to validate the value before submitting the form, just pass the value to you validator this way :

    validator: (val) => Validators().validateEmail(val)
    

    and update your validateEmail to accept the parameter.

    Also if you want to remove only trailing spaces use the trimRight() function.

    As an example, this work perfectly on my side :

    class Validators {
      static String validateEmail(String value) {
        String 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 regExp = new RegExp(pattern);
        if (value == null || value.length <= 0) {
          return "Email is Required";
        } else if (!regExp.hasMatch(value)) {
          return "Invalid Email";
        } else {
          return null;
        }
      }
    }
    
    TextFormField(
      maxLines: 1,
      inputFormatters: [LengthLimitingTextInputFormatter(128)],
      validator: (val) => Validators.validateEmail(val.trimRight()),
      onSaved: (val) => _currMember.email = val,
      initialValue: _currMember.email,
    ),