validateUsername static method

String? validateUsername(
  1. String? username
)

Validates the username input.

  • username: The username to be validated.

Returns a string error message if the username is invalid, otherwise null.

Implementation

static String? validateUsername(String? username) {
  if (username == null || username.isEmpty) {
    return 'Username is required.'; // Return error message if username is empty.
  }

  // Define a regular expression pattern for the username.
  const pattern = r"^[a-zA-Z0-9_-]{3,20}$";

  // Create a RegExp instance from the pattern.
  final regex = RegExp(pattern);

  // Check if the username matches the pattern.
  bool isValid = regex.hasMatch(username);

  // Ensure the username doesn't start or end with an underscore or hyphen.
  if (isValid) {
    isValid = !username.startsWith('_') &&
        !username.startsWith('-') &&
        !username.endsWith('_') &&
        !username.endsWith('-');
  }

  if (!isValid) {
    return 'Username is not valid.'; // Return error message if the username is invalid.
  }

  return null; // Return null if the username is valid.
}