Johan Jomy
Johan Jomy

Reputation: 691

How to check if a string only contains letters, numbers, underscores and period. Flutter/Dart

I want to check if a string only contains:

  1. Letters
  2. Numbers
  3. Underscores
  4. Periods

in Flutter, I tried the following to get only the letters but even if other characters are there it returns true if it contains a letter:

String mainString = "abc123";

print(mainString.contains(new RegExp(r'[a-z]')));

As I told it returns true since it contains letters, but I want to know if it only contains letters.

Is there a way to do that?

Upvotes: 7

Views: 18620

Answers (2)

jamesdlin
jamesdlin

Reputation: 90175

The problem with your RegExp is that you allow it to match substrings, and you match only a single character. You can force it to require that the entire string be matched with ^ and $, and you can match against one or more of the expression with +:

print(RegExp(r'^[a-z]+$').hasMatch(mainString));

To match all the characters you mentioned:

print(RegExp(r'^[A-Za-z0-9_.]+$').hasMatch(mainString));

Upvotes: 27

Abbasihsn
Abbasihsn

Reputation: 2171

the basic way of doing this is as follow:

  1. define a list of acceptable characters:
// for example
List<String> validChar = ["1", "2", "3", "t"];
  1. loop through all character of your string and check its validity:
  // given text
  String x = "t5";
  
  bool valid = true;
  for(int i=0; i<x.length; i++){
    if(!validChar.contains(x[i])){
      valid = false;
    }
  }
  print(valid);

just change the x and validChar as your need.

Upvotes: 2

Related Questions