Home > OS >  Dart Regular Expression Validating the length
Dart Regular Expression Validating the length

Time:11-24

I am beginner to dart. I have tried using regular expression to validate the length of string. But its not working as expected. The {} curly braces indicate a length range in regex. Using {12} means a length of exactly 12, {12,15} means a length of 12 to 15 characters, and {12,} means a length of at least 12 with no upper limit. Because {12,} follows the . character, allowing 12 or more of any character. I have done based on this.

        const password = r"dsjRK@#RDsk34$SwedfQWDF";
        if (!password.contains(RegExp(r'[a-z]'))) {
          print('password should  contain atleast lower case character');
        } else if (!RegExp(r'[A-Z]').hasMatch(password)) {
          print('password should contain atleast lower case character');
        } else if (!RegExp(r'[0-9]').hasMatch(password)) {
          print('password should contain atleast one digits');
        } else if (!RegExp(r'[$@#%&*^!]').hasMatch(password)) {
          print('password should contain atleast one special charatcer');
        } else if (!RegExp(r'.{12,15}').hasMatch(password)) {
          print('password atleast 12 max 15 digits');
        }  else {
          print("Perfect Password");
       }

OutPUT: Perfect Password

We can use some other solutions also . But my doubt is min length validation is working , why maximum validation is not working ?Please help me to understand the issue.

CodePudding user response:

Based on the text of this matcher: {12, 15} it seems like you'd want to have maximum of 15 characters allowed. So change to this, if you want to have separate print-outs for the different cases:

  const password = r"dsjRK@#RDsk34$SwedfQWDF";
  if (!RegExp(r'[a-z]').hasMatch(password)) {
    print('password should contain at least one lower case character');
  } else if (!RegExp(r'[A-Z]').hasMatch(password)) {
    print('password should contain at least lower case character');
  } else if (!RegExp(r'[0-9]').hasMatch(password)) {
    print('password should contain at least one digits');
  } else if (!RegExp(r'[$@#%&*^!]').hasMatch(password)) {
    print('password should contain at least one special charatcer');
  } else if (password.length < 12) {
    print('password at least 12 characters');
  } else if (password.length > 15) {
    print('password should have max 15 characters');
  } else {
    print("Perfect Password");
  }

I also changed the first if statement to be consistent with the rest...

CodePudding user response:

Change the regex with this one r'^.{12,15}$'.

It literally means that the substring generated from 12th to 15th character should be at the end of the original string

else if (!RegExp(r'^.{12,15}$').hasMatch(password){
     print('password atleast 12 max 15 digits');
}
  •  Tags:  
  • dart
  • Related