H Zan
H Zan

Reputation: 387

How do I use regexp in flutter?

enter image description here I want the format shown in the photo. I used this code

RegExp(r'^(?=.*[0-9])(?=\\S+$).{8,40}$').hasMatch(text).

This code is ok for Java but not for Dart. Why is that?

Upvotes: 1

Views: 8896

Answers (2)

InnerPeace
InnerPeace

Reputation: 31

Maybe there is your entire solution function for checking valid constraint of the password as well as using regex expression in Dart.

String? validatePassword(String? value) {
        String missings = "";
        if (value!.length < 8) {
          missings += "Password has at least 8 characters\n";
        }

        if (!RegExp("(?=.*[a-z])").hasMatch(value)) {
          missings += "Password must contain at least one lowercase letter\n";
        }
        if (!RegExp("(?=.*[A-Z])").hasMatch(value)) {
          missings += "Password must contain at least one uppercase letter\n";
        }
        if (!RegExp((r'\d')).hasMatch(value)) {
          missings += "Password must contain at least one digit\n";
        }
        if (!RegExp((r'\W')).hasMatch(value)) {
          missings += "Password must contain at least one symbol\n";
        }

        //if there is password input errors return error string
        if (missings != "") {
          return missings;
        }

        //success
        return null;
 }

there's my result image

Upvotes: 1

Emma
Emma

Reputation: 27723

My guess is that double-backslashing might be unnecessary, and:

^(?=.*[0-9])(?=\S+$).{8,40}$

might simply work.


Maybe, you might want to a bit strengthen/secure the pass criteria, maybe with some expression similar to:

(?=.*[0-9])(?=.*[A-Za-z])(?=.*[~!?@#$%^&*_-])[A-Za-z0-9~!?@#$%^&*_-]{8,40}$

which allows,

  • a minimum of one digit,
  • a minimum of one upper/lower case, and
  • at least one of these chars: ~!?@#$%^&*_-

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Reference

Upvotes: 7

Related Questions