Flutter 我创建了一个登录页面,我需要将这些内容添加到我的用户名中。我如何在颤振中验证我的形式

Flutter 我创建了一个登录页面,我需要将这些内容添加到我的用户名中。我如何在颤振中验证我的形式,flutter,Flutter,至少1个字母 最少1个 仅允许使用字符(41; 它失败了 Pattern pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[_]).{8,}$'; RegExp regex = new RegExp(pattern); 您需要在服务器上使用验证器。您需要在validator函数中添加一个条件来检查它是否为false,并返回希望用户看到的错误消息 您可以使用autovalidate:true进行验证,也可以在保存前在表单上使用.cu

至少1个字母 最少1个 仅允许使用字符(41;

它失败了

 Pattern pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[_]).{8,}$';
RegExp regex = new RegExp(pattern);

您需要在服务器上使用验证器。您需要在validator函数中添加一个条件来检查它是否为false,并返回希望用户看到的错误消息

您可以使用autovalidate:true进行验证,也可以在保存前在表单上使用.currentState.validate()手动进行验证

所以你的代码看起来像这样

validator: (value) {
  final alphanumeric = RegExp(YOUR_REGEX_HERE);
  if (!alphanumeric.hasMatch(value)) return 'YOUR_ERROR_MESSAGE';
}

请查看我创建的示例:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  TextEditingController userName = TextEditingController();

  FocusNode usernameFocus = new FocusNode();
  String errorText;
  bool _isValid = false;

  @override
  void initState() {
    super.initState();

    userName.addListener(() {
      String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[_]).{8,}$';
      RegExp regExp = new RegExp(pattern);

      if (userName.text.isEmpty) {
        setState(() {
          errorText = 'Field cannot be empty';
        });
      } else {
        if (!regExp.hasMatch(userName.text)) {
          print('The does not  matches the requirement');
          setState(() {
            // here you can add you text
            errorText =
                'Minimum 1 Capital letter, 1 small letter and 1 number and _';
            _isValid = false;
          });
        } else {
          print('the value matches');
          setState(() {
            errorText = null;
            _isValid = true;
          });
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(left: 20, right: 20),
              child: TextField(
                focusNode: usernameFocus,
                decoration: new InputDecoration(
                  errorText: errorText,
                  prefixIcon: Icon(
                    Icons.supervised_user_circle,
                    color: Color(0xFF282858),
                  ),
                  labelText: "UserName",
                  labelStyle: TextStyle(
                      fontFamily: "Poppins-Medium",
                      color: usernameFocus.hasFocus
                          ? Colors.grey[600]
                          : Colors.grey[600]),
                  fillColor: Colors.white,
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey[400], width: 2.0),
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  border: new OutlineInputBorder(
                    borderRadius: new BorderRadius.circular(10.0),
                    borderSide:
                        new BorderSide(color: Colors.grey[400], width: 2.0),
                  ),
                  //fillColor: Colors.green
                ),
                controller: userName,
                keyboardType: TextInputType.text,
              ),
            ),
            RaisedButton(
              child: Text('Login'),
              onPressed: () {
                print(_isValid);

                if (!_isValid) {
                  return;
                }
                print('validation sucess');
              },
            )
          ],
        )),
      ),
    );
  }
}


导入“包装:颤振/材料.省道”;
void main()=>runApp(MyApp());
类MyApp扩展了StatefulWidget{
@凌驾
_MyAppState createState()=>\u MyAppState();
}
类MyAppState扩展了状态{
TextEditingController用户名=TextEditingController();
FocusNode usernameFocus=新FocusNode();
字符串错误文本;
bool _isValid=false;
@凌驾
void initState(){
super.initState();
userName.addListener(){
字符串模式=r'^(?=.[A-Z])(?=.[A-Z])(?=.[0-9])(?=..[[u]){8,}$';
RegExp RegExp=新的RegExp(模式);
if(userName.text.isEmpty){
设置状态(){
errorText='字段不能为空';
});
}否则{
如果(!regExp.hasMatch(userName.text)){
打印(“不符合要求”);
设置状态(){
//在这里你可以添加你的文字
错误文本=
“至少1个大写字母、1个小写字母、1个数字和u3;”;
_isValid=false;
});
}否则{
打印(“值匹配”);
设置状态(){
errorText=null;
_isValid=true;
});
}
}
});
}
@凌驾
小部件构建(构建上下文){
返回材料PP(
debugShowCheckedModeBanner:false,
家:脚手架(
正文:中(
子:列(
mainAxisAlignment:mainAxisAlignment.center,
crossAxisAlignment:crossAxisAlignment.center,
儿童:[
填充物(
填充:仅限常量边集(左:20,右:20),
孩子:TextField(
focusNode:usernameFocus,
装饰:新的输入装饰(
errorText:errorText,
前缀:图标(
图标。受监督的用户圈,
颜色:颜色(0xFF282858),
),
labelText:“用户名”,
标签样式:文本样式(
fontFamily:“罂粟中等”,
颜色:usernameFocus.hasFocus
?颜色。灰色[600]
:颜色。灰色[600]),
fillColor:Colors.white,
聚焦顺序:大纲输入边框(
borderSide:borderSide(颜色:Colors.grey[400],宽度:2.0),
边界半径:边界半径。圆形(10.0),
),
边框:新大纲输入边框(
边界半径:新边界半径。圆形(10.0),
边界:
新边框(颜色:颜色。灰色[400],宽度:2.0),
),
//fillColor:Colors.green
),
控制器:用户名,
键盘类型:TextInputType.text,
),
),
升起的按钮(
子项:文本('Login'),
已按下:(){
打印(_是有效的);
如果(!\u有效){
返回;
}
打印(“验证成功”);
},
)
],
)),
),
);
}
}

让我知道它是否有效。

您可以使用此库

公开发行

flatter\u form\u生成器:^3.7.3

代码如下所示:

GlobalKey _addextKey=GlobalKey()

FormBuilder(
键:_addextKey,
子:ListView(
儿童:[
TextFormField(
textInputAction:textInputAction.next,
风格:textStyle,
控制器:_NameauthController,
//忽略:缺少返回
验证程序:FormBuilderValidators.required(),
装饰:输入装饰(
hintText:'名称',
hintStyle:TextStyle(fontSize:12.0),
标签样式:文本样式,
错误样式:
TextStyle(颜色:Colors.red,字体大小:12.0),
边框:大纲输入边框(
边界半径:边界半径。圆形(5.0)),
键盘类型:TextInputType.text,
),
]);),
       FormBuilder(
        key: _addextKey,
        child: ListView(
          children: <Widget>[
           TextFormField(
            textInputAction: TextInputAction.next,
            style: textStyle,
            controller: _NameauthController,
         // ignore: missing_return
            validator: FormBuilderValidators.required(),
            decoration: InputDecoration(
                hintText: 'name',
                hintStyle: TextStyle(fontSize: 12.0),
                labelStyle: textStyle,
                errorStyle:
                    TextStyle(color: Colors.red, fontSize: 12.0),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5.0))),
            keyboardType: TextInputType.text,
          ),
         ]);),