Creat function usernameValidation(str) take the str parameter being passed and determine if the string is a valid username according to the following rules:
- The username is between 4 and 25 characters.
- It must start with a letter.
- It can only contain letters, numbers, and the underscore character.
- It cannot end with an underscore character.
Solution:
function usernameValidation($str) {
$return = true;
////////////////// 4 to 25 character////////////
if ($return) {
if (!(strlen($str) >= 4 && strlen($str) <= 25)) {
$return = false;
}
}
////////////////// 4 to 25 character////////////
////////////////// Must start with Number ////////////
if ($return) {
$asciiCode = ord($str[0]);
if (!(($asciiCode >= 97 && $asciiCode <= 122) || ($asciiCode >= 65 && $asciiCode <= 90))) {
$return = false;
}
}
////////////////// Must start with Number ////////////
///////////// It can only contain letters, numbers, and the underscore character.///////////
if ($return) {
for ($i = 0; $i < strlen($str); $i++) {
$asciiCode = ord($str[$i]);
if (!( ($asciiCode >= 97 && $asciiCode <= 122) || ($asciiCode >= 65 && $asciiCode <= 90) || ($asciiCode >= 48 && $asciiCode <= 57) || ($asciiCode == 95))) {
$return = false;
break;
}
}
}
///////////// It can only contain letters, numbers, and the underscore character.///////////
///////////It cannot end with an underscore character.///////////
if ($return) {
$asciiCode = ord($str[$i - 1]);
if ($asciiCode == 95) {
$return = false;
}
}
///////////It cannot end with an underscore character.///////////
return $return ? 'true' : 'false';
}
