Meggy
Meggy

Reputation: 1671

Validate TextFormField in Flutter - What's wrong with this Regex?

I need to check a TextFormField to ensure the user only inputs alphanumeric characters with no spaces or other symbols.

I'm using The Validator plugin for flutter to validate my TextFormField.

I've created a controller;

               var _tag1Controller = TextEditingController();

and a Regex validator;

               TextFormField(
                          controller: _tag1Controller,
                          validator: FieldValidator.regExp(RegExp('^[a-zA-Z0-9\-_]\$'),'No hash/space'),
                          textAlign: TextAlign.center,
                          decoration: new InputDecoration(
                            hintText: 'Enter Tag 1',                        
                          ),
                            onChanged: (tag1text) {
                            setState(() {
                              this.tag1 = tag1text;
                            });
                          },
                        ),      

If the user inputs a hashtag or whitespace a message comes up which says 'No hash/space'.

But instead, the 'No hash/space' message comes up no matter what the user inputs - even if it's clean with no symbols or spaces.

Can anyone see what's wrong with my Regex?

Upvotes: 0

Views: 1262

Answers (2)

The fourth bird
The fourth bird

Reputation: 163217

If you want to match 1 or more characters, you have to repeat the character class one or more times using + or else it will match a single character.

If you want to assert the end of the string, you can use $ without escaping.

Note that you don't have to escape the - in this case, but often this is either put at the start or at the end to prevent accidentally use it as a range.

r'^[a-zA-Z0-9_-]+$'

Upvotes: 1

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use raw string literals, do not escape $ in the end of string meaning and keep - to the edge of character classes.

Also, [a-zA-Z0-9_] = \w.

Use

validator: FieldValidator.regExp(RegExp(r'^[\w-]$'),'No hash/space'),

Upvotes: 0

Related Questions