dart Flutter中的文本字段确认

gijlo24d  于 2023-02-10  发布在  Flutter
关注(0)|答案(5)|浏览(153)

我正在处理Flutter TextField小部件。如果用户没有填充TextField,我希望在TextField小部件下面显示错误消息。在这种情况下,我只需要使用TextField小部件,而不是TextFormField

e7arh2l6

e7arh2l61#

你想要什么的最小例子:

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() {
    return new MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  final _text = TextEditingController();
  bool _validate = false;

  @override
  void dispose() {
    _text.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextField Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Error Showed if Field is Empty on Submit button Pressed'),
            TextField(
              controller: _text,
              decoration: InputDecoration(
                labelText: 'Enter the Value',
                errorText: _validate ? 'Value Can\'t Be Empty' : null,
              ),
            ),
            RaisedButton(
              onPressed: () {
                setState(() {
                  _text.text.isEmpty ? _validate = true : _validate = false;
                });
              },
              child: Text('Submit'),
              textColor: Colors.white,
              color: Colors.blueAccent,
            )
          ],
        ),
      ),
    );
  }
}
deyfvvtc

deyfvvtc2#

Flutter自己处理错误文本,所以我们不需要使用变量_validate,它会在运行时检查你是否满足条件。

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;
}

注意:用户必须至少添加一个字符才能获得此错误消息。

wlwcrazw

wlwcrazw3#

我会考虑将TextFormFieldvalidator一起使用。
示例:

class MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextFormField validator'),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextFormField(
              decoration: InputDecoration(
                hintText: 'Enter text',
              ),
              textAlign: TextAlign.center,
              validator: (text) {
                if (text == null || text.isEmpty) {
                  return 'Text is empty';
                }
                return null;
              },
            ),
            RaisedButton(
              onPressed: () {
                if (_formKey.currentState.validate()) {
                  // TODO submit
                }
              },
              child: Text('Submit'),
            )
          ],
        ),
      ),
    );
  }
}
0yg35tkg

0yg35tkg4#

  • 如果您使用TextFormField,那么您可以轻松实现“文本字段下方的错误”。
  • 您可以在不使用_validate或任何其他标志的情况下执行此操作。
  • 在这个例子中,我使用了TextFormField小部件的validator方法,这使得工作更容易,同时可读性也更强。
  • 我还使用了FormState,以使工作更加轻松
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final _form = GlobalKey<FormState>(); //for storing form state.

//saving form after validation  
void _saveForm() {
    final isValid = _form.currentState.validate();
    if (!isValid) {
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Form(
          key: _form, //assigning key to form

          child: ListView(
            children: <Widget>[

              TextFormField(
                decoration: InputDecoration(labelText: 'Full Name'),
                validator: (text) {
                  if (!(text.length > 5) && text.isNotEmpty) {
                    return "Enter valid name of more then 5 characters!";
                  }
                  return null;
                },
              ),

              TextFormField(
                decoration: InputDecoration(labelText: 'Email'),
                validator: (text) {
                  if (!(text.contains('@')) && text.isNotEmpty) {
                    return "Enter a valid email address!";
                  }
                  return null;
                },
              ),

              RaisedButton(
                child: Text('Submit'),
                onPressed: () => _saveForm(),
              )
            ],
          ),
        ),
      ),
    );
  }
}

"希望这能帮上忙"

gfttwv5a

gfttwv5a5#

对于文本字段和文本表单字段的验证,你可以使用这个例子,我希望这对你们有帮助。

TextField(
                          enableInteractiveSelection: true,
                          autocorrect: false,
                          enableSuggestions: false,
                          toolbarOptions: ToolbarOptions(
                            copy: false,
                            paste: false,
                            cut: false,
                            selectAll: false,
                          ),
                          controller: _currentPasswordController,
                          obscureText: passwordVisible,
                          decoration: InputDecoration(
                            errorText: Validators.password(
                                _currentPasswordController.text),
                            filled: true,
                            fillColor: Colors.white,
                            contentPadding:
                                const EdgeInsets.fromLTRB(20, 24, 12, 16),
                            border: const OutlineInputBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(8.0))),
                            // filled: true,
                            labelText: 'Password',
                            hintText: 'Enter your password',
                            suffixIcon: GestureDetector(
                              onTap: () {
                                setState(() {
                                  passwordVisible = !passwordVisible;
                                });
                              },
                              child: Container(
                                  margin: const EdgeInsets.all(13),
                                  child: Icon(
                                      passwordVisible
                                          ? FontAwesomeIcons.eyeSlash
                                          : Icons.remove_red_eye_sharp,
                                      color: ColorUtils.primaryGrey,
                                      size: 25)),
                            ),
                          ),
                        ),

验证消息示例代码

static password(String? txt) {
if (txt == null || txt.isEmpty) {
  return "Invalid password!";
}
if (txt.length < 8) {
  return "Password must has 8 characters";
}
if (!txt.contains(RegExp(r'[A-Z]'))) {
  return "Password must has uppercase";
}
if (!txt.contains(RegExp(r'[0-9]'))) {
  return "Password must has digits";
}
if (!txt.contains(RegExp(r'[a-z]'))) {
  return "Password must has lowercase";
}
if (!txt.contains(RegExp(r'[#?!@$%^&*-]'))) {
  return "Password must has special characters";
} else
  return;
}

相关问题