Textfield validation in Flutter

前端 未结 4 1121
你的背包
你的背包 2020-12-08 18:13

I am working on Flutter TextField widget. I want to show an error message below the TextField widget if the user does not fill that TextField

4条回答
  •  无人及你
    2020-12-08 19:06

    Adding to @anmol answer: TextFormField is also a better option for validation.

    Flutter handles error text itself, so we don't require to use variable _validate. It will check at runtime whether you satisfied the condition or not.

    final confirmPassword = TextFormField(
      controller: widget.confirmPasswordController,
      obscureText: true,
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.lock_open, color: Colors.grey),
        hintText: 'Confirm Password',
        errorText: validatePassword(widget.confirmPasswordController.text),
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
      ),
    );
    
    String validatePassword(String value) {
      if (!(value.length > 5) && value.isNotEmpty) {
        return "Password should contain more than 5 characters";
      }
      return null;
    }
    

    Note: User must add at least one character to get this error message.

提交回复
热议问题