我有一个TextFormField
使用验证器检查输入是否满足一组要求的方法。如果输入不满足特定要求,则红色的错误文本将相应地通知用户。如果密码满足所有要求,我想返回绿色文本(“安全密码”)。
class RegForm extends StatefulWidget {
const RegForm({Key? key}) : super(key: key);
@override
_RegFormState createState() => _RegFormState();
}
class _RegFormState extends State<RegForm> {
Color errorClr = Colors.red;
final String checkAll =
r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$';
final String checkLetters = r'^(?=.*?[A-Z])(?=.*?[a-z])';
final String checkNumbers = r'^(?=.*?[0-9])';
@override
Widget build(BuildContext context) {
return Scaffold(
body: TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a valid password';
} else {
if (value.length < 8)
return 'Password has to be 8 characters or more!';
else if (!RegExp(checkLetters).hasMatch(value))
return 'Password has to contain Uppercase and Lowercase letters!';
else if (!RegExp(checkNumbers).hasMatch(value))
return 'Password has to contain numbers!';
else if (RegExp(checkAll).hasMatch(value)) {
errorClr = Colors.green;
return 'Very secure password!';
}
}
errorClr = Colors.green;
return 'Secure password!';
},
decoration: InputDecoration(
errorStyle: TextStyle(
color: errorClr,
),
contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
hintText:
'Password must be at least 8 characters long, contains numbers and both upper and lowercase letters',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
);
}
}
上面的代码不会以绿色返回“安全密码”文本,我认为它是因为验证器不会重建小部件,因此errorStyle
不会更新。有没有办法使这项工作?