我有2个表单域,我想验证第二个表单域以匹配第一个表单域的密码,我尝试了但没有成功..谢谢回答。
更新:我已经具有提交按钮及其功能,我想要第二个字段中的Validator来验证第一个字段文本以匹配第二个字段。
new TextFormField(
controller: _registerPassController,
decoration: new InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) =>
value.isEmpty ? 'Password can\'t be empty' : null,
onSaved: (value) => _password = value,
),
],
),
new Stack(
alignment: const Alignment(1.0, 1.0),
children: <Widget>[
new TextFormField(
controller: _registerPassController2,
decoration: new InputDecoration(labelText: 'Retype Password'),
obscureText: true,
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
},),
Run Code Online (Sandbox Code Playgroud)
ZoR*_*oRa 14
我终于找到了答案,实际上它是如此简单。
new TextFormField(
controller: _registerPassController2,
decoration: new InputDecoration(labelText: 'Retype Password'),
obscureText: true,
validator: (value) {
if (value != _registerPassController.text) {
return 'Password is not matching';
}
},
),
Run Code Online (Sandbox Code Playgroud)
suh*_*air 12
由于您使用的是formfield,因此使用键访问其他字段的值将是适当的。您可以这样声明全局密钥
var passKey = GlobalKey<FormFieldState>();
然后将其传递到密码字段以在验证过程中检索其值。
TextFormField(
key: passKey,
obscureText: true,
decoration: InputDecoration(
labelText: "Password"
),
validator: (password){
var result = password.length < 4 ? "Password should have at least 4 characters" : null;
return result;
},
);
Run Code Online (Sandbox Code Playgroud)
然后,您可以像这样在确认验证器中使用密码
TextFormField(
obscureText: true,
decoration: InputDecoration(
labelText: "Confirm Password"
),
validator: (confirmation){
var password = passKey.currentState.value;
return equals(confirmation, password) ? null : "Confirm Password should match password";
},
);
Run Code Online (Sandbox Code Playgroud)
我这样做的方法是验证提交按钮,然后显示一条消息。
String _password;
Widget _passwordField() {
return new TextFormField(
autocorrect: false,
obscureText: true,
decoration: InputDecoration(labelText: 'Password'),
validator: (value) =>
value.isEmpty ? "Password can't be empty" : null,
onSaved: (val) => _password = val;
}
String _passwordConfirm;
Widget _passwordConfirmField() {
return new TextFormField(
autocorrect: false,
obscureText: true,
decoration: InputDecoration(labelText: 'Retype Password'),
validator: (value) =>
value.isEmpty ? "Password can't be empty" : null,
onSaved: (val) => _passwordConfirm = val;
}
final formKey = new GlobalKey<FormState>();
Widget _buildForm() {
return new Form(
autovalidate: true,
key: formKey,
child: new Column(children: <Widget>[
_passwordField(),
_passwordConfirmField(),
new RaisedButton(
child: Text('Sign Up'),
onPressed: () => submit()
)
]
}
void submit() {
final form = formKey.currentState;
if (form.validate()) {
form.save(); //this will cause the onSaved method to get called
//you will need to do some additional validation here like matching passwords
if(_password != _passwordConfirm) {
showDialog(....)
} else {
//complete
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:这是一个StatefulWidget
| 归档时间: |
|
| 查看次数: |
5068 次 |
| 最近记录: |