Home > Enterprise >  the regular expression pattern does not work in form validation for flutter
the regular expression pattern does not work in form validation for flutter

Time:01-13

I am trying to make validation and I want to check if user's input contains numbers and letters. So I created this code but somehow it doesn't work. It doesn't reach the first print, but it seems like everything is ok.

my code:

final GlobalKey<FormState> _key = GlobalKey<FormState>();


  @override
  Widget build(BuildContext context) {
    return Form(
      key: _key,
      child: TextFormField(
          decoration: InputDecoration(
            focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(5.0)),
                borderSide: BorderSide(
                  color: Colors.blue,
                  width: 2,
                )),
          ),
          validator: (value) {
            if (value == null || value.isEmpty) {
              print(value);
              print('iam here');
              return 'Plate number is required';

            }
            String pattern = r'[!@#<>?":_`~;[\]\\|= )(*&^%0-9-]';
            if (!RegExp(pattern,  caseSensitive: false, unicode: true, dotAll: true).hasMatch(value)) return 'invalid form';
            return null;
          }),

CodePudding user response:

I like to do the validations with regex in this way

TextFormField(inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.allow(RegExp("r'^[a-zA-Z0-9] $'"))]
  •  Tags:  
  • Related