GDTyka
GDTyka

Reputation: 530

Flutter how to validate password input field with regex

I use regex validation in my custom textfield listener, to check if password valid

this is my validation code

            RegExp regexUpper = RegExp(r'^(?=.*[A-Z])$');
            RegExp regexLower = RegExp(r'^(?=.*[a-z])$');
            RegExp regexLength = RegExp(r'^.{8,}$');

            if (!regexLength.hasMatch(value.toString())) {
              return 'Пароль слишком короткий';
            }
            if (!regexLower.hasMatch(value.toString())) {
              print(value);
              return 'Пароль должен содержать хотя бы одну маленькую букву';
            }
            if (!regexUpper.hasMatch(value.toString())) {
              return 'Введите хотя бы одну заглавную букву';
            }
            return null;

regexLength work correctly but other not.

What i did wrong and how i can fix it ?

Upvotes: 0

Views: 363

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You should not use lookarounds wrapped with anchors.

You can fix the issues with

RegExp regexUpper = RegExp(r'[A-Z]');
RegExp regexLower = RegExp(r'[a-z]');
RegExp regexLength = RegExp(r'^.{8,}$');

Look: ^(?=.*[A-Z])$ asserts the current position at the start of string (^), then checks if there is an uppercase ASCII letter ([A-Z]) anywhere after zero or more chars other than line break chars (as many as possible, with .*), and then requires the end of string ($) (right at the start of string). This is an example of a pattern that never matches any string.

Upvotes: 1

Related Questions