为什么Regex表达式在flutter中不按预期工作

eaf3rand  于 2023-05-19  发布在  Flutter
关注(0)|答案(3)|浏览(118)

在我的应用程序中,我验证年龄,电话,电子邮件和更多的领域,我试图验证所有这些领域的形式。但无法做到这一点,我有正则表达式电话textformfield。我不能使用inputFormatters,因为我有自定义textformfield。
我希望我的应用程序字段应该只包含10位数字,避免所有特殊字符和空格。
我该如何解决这个问题?
下面是我的代码:

TextFormFieldCustom(                                
                                  hintText: "Mobile Number",
                                  enable: _mobileController.text.isEmpty,
                                  controller: _mobileController,
                                  keyboardType: TextInputType.number,
                                  inputTextFormatter: [
                                    
 FilteringTextInputFormatter.digitsOnly 
                                  ],
                                  validator: (value) {
                                    if (!isValidMobile(value!)) {
                                      return 'Please enter your correct mobile number';
                                    }
                                    return null;
                                  },
                                ),

这是我的自定义文本字段,我在应用程序中的许多领域使用:

class TextFormFieldCustom extends StatefulWidget {
  final String hintText;
  final String? labelText;
  final List<TextInputFormatter>? inputTextFormatter;
  final TextEditingController? controller;
  final Widget? prefixIcon;
  final String? Function(String?)? validator;
  final Function(String?)? onChanged;
  final TextInputType? keyboardType;
  final Function(String?)? onSubmitted;
  final int? maxLines;
  final int? lenth;
  final bool enable;
  final double height;
  final Color? color;
  const TextFormFieldCustom({
    Key? key,
    required this.hintText,
    this.labelText,
    this.controller,
    this.prefixIcon,
    this.height = 65,
    this.validator,
    this.onChanged,
    this.keyboardType,
    this.onSubmitted,
    this.lenth,
    this.maxLines = 1,
    this.enable = true,
    this.color, this.inputTextFormatter,
  }) : super(key: key);

  @override
  State<TextFormFieldCustom> createState() => _TextFormFieldCustomState();
}

class _TextFormFieldCustomState extends State<TextFormFieldCustom> {
  bool isValid = false;
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.height.h,
      child: TextFormField(
        controller: widget.controller,
        validator: (value) {
          String? valid;
          if (widget.validator != null) {
            valid = widget.validator!(value);
          }
          if (valid == null && value!.isNotEmpty) {
            setState(() {
              isValid = true;
            });
          } else {
            setState(() {
              isValid = false;
            });
          }
          return valid;
        },
        onChanged: widget.onChanged,
        maxLines: widget.maxLines,
        maxLength: widget.lenth,
        keyboardType: widget.keyboardType,
        inputFormatters: [FilteringTextInputFormatter.singleLineFormatter,],
        onFieldSubmitted: (String value) {
          //for hiding keyboard
          //FocusScope.of(context).requestFocus(FocusNode());

          if (widget.onSubmitted != null) {
            widget.onSubmitted!(value);
          }
        },
        style: TextStyle(
          color: Colors.black,
          fontSize: 14.sp,
          fontWeight: FontWeight.w500,
        ),
        autofocus: false,
        autocorrect: true,
        enabled: widget.enable,
        autovalidateMode: AutovalidateMode.disabled,
        decoration: InputDecoration(
          filled: true,
          fillColor: widget.color ?? CustomColors.peachColor,
          hintText: widget.hintText,
          labelText: widget.labelText,
          hintStyle: TextStyle(
            color: CustomColors.greyFont,
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.r),
            borderSide: BorderSide.none,
          ),
          contentPadding:
              EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.r),
            borderSide: const BorderSide(color: Colors.black),
          ),
          prefixIcon: widget.prefixIcon,
          suffixIcon: isValid
              ? const Icon(Icons.check_circle, color: Colors.green)
              : null,
        ),
      ),
    );
  }
}

这是在我的应用程序中发生的:

ztyzrc3y

ztyzrc3y1#

只需将inputFormatters参数添加到TextFormField。

import 'package:flutter/services.dart'; 
import 'dart:io';

TextFormField(
      controller: mobileController, // textfield controller
      keyboardType: Platform.isIOS
          ? const TextInputType.numberWithOptions(signed: true)
          : TextInputType.phone,
      inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp("[0-9]")), // or FilteringTextInputFormatter.digitsOnly
      ],
      formValidator: (value) {
          //...your validation
      },
    )

用于打开数字(拨号)键盘。

keyboardType: Platform.isIOS
          ? const TextInputType.numberWithOptions(signed: true)
          : TextInputType.phone,

如果您有自定义文本字段小部件,则在以下片段中使用

class AppTextField extends StatelessWidget {
//... other parameter
final List<TextInputFormatter>? inputTextFormatter;
final TextInputType? keyboardType;

const AppTextField({
    Key? key,
    //... other parameter
    this.inputTextFormatter,
    this.keyboardType,
 }) : super(key: key);

@override
  Widget build(BuildContext context) {
    return TextFormField(
    inputFormatters: inputTextFormatter ??
          [FilteringTextInputFormatter.singleLineFormatter],
    keyboardType: keyboardType ?? TextInputType.emailAddress,
    );
  }
}

这里,是如何称呼它。

AppTextField(
/// ... other parameter
keyboardType: isIOS
          ? const TextInputType.numberWithOptions(signed: true)
          : TextInputType.phone,
      inputTextFormatter: [
        FilteringTextInputFormatter.allow(RegExp("[0-9]")), // or FilteringTextInputFormatter.digitsOnly
      ],
 );
mrzz3bfm

mrzz3bfm2#

我不能使用inputFormatters,因为我有自定义textformfield。
它接受空格和所有特殊字符
两者都不可能同时发生。要么你必须使用接受inputFormatters的textfield,要么你可以只放置验证和显示消息。
以上粘贴的解决方案应适用于第二种情况。

j0pj023g

j0pj023g3#

使用https://dartpad.dev/?id=0ef68e8905ca3277049e23ba3e1645e7

bool isValidMobile(String mobile) {
    if (mobile.length > 10) {
        mobile = mobile.substring(3);
      }
    String patttern = r'([0-9]{10}$)';
    RegExp regExp = new RegExp(patttern);
    if (mobile.length == 0 || mobile.length != 10) {
          return false;
    }
    else if (!regExp.hasMatch(mobile)) {
          return false;
    }
    return true;
}

相关问题