isValidUsername method
Checks whether the string is a valid username.
Validation Rules:
- Must be at least 3 characters long.
- Can only contain letters (A-Z, a-z), numbers (0-9), and underscores (_)
- Spaces or special characters are NOT allowed.
Returns:
true
if the username is valid.false
if the username is invalid.
Example Usage:
String username1 = "user_123";
bool isValid1 = username1.isValidUsername(); // true
String username2 = "ab";
bool isValid2 = username2.isValidUsername(); // false (too short)
String username3 = "user@name";
bool isValid3 = username3.isValidUsername(); // false (contains @ symbol)
String username4 = "User_Name_99";
bool isValid4 = username4.isValidUsername(); // true
Edge Cases:
- Usernames shorter than 3 characters are invalid.
- Usernames with spaces or special characters (e.g.,
@, #, $, %
) are invalid. - Usernames with only numbers are valid, e.g.,
"12345"
.
Implementation
bool isValidUsername() {
return RegExp(r'^[a-zA-Z0-9_]{3,}$').hasMatch(this);
}