0

My objective is to let the form warn a user if the username input does not start with a letter. Unfortunately, the condition is still true despite the entered username starting with a letter.

The code below is the variable which contains an array for storing all 26 both uppercase and lowercase letters.

$alphas = array_merge(range('a', 'z'), range('A', 'Z'));

Then the code below is used to output the error message.

if (empty($username)){
    array_push($errors, "*Username cannot be blank<br>");
}else if(!preg_match("/^[a-zA-Z0-9_]*$/",$username)){
    array_push($errors, "*Username can only contain alpha-numeric characters or an underscore<br>");
}else if($username[0] !== $alphas){
    array_push($errors, "*Username must begin with a letter<br>");
}

The condition is "if($username[0] !== $alphas)", however it keeps returning TRUE, meaning it will show the message "*Username must begin with a letter" regardless the first letter of the username input.

How can I get through this problem?

  • 1
    `!==` is an equality operator, it won't check whether or not an element exists in an array (hint: [`in_array`](http://php.net/manual/en/function.in-array.php)). Alternatively, since you're already using a regex to validate the submission, you could just modify it to check the first character separately. – iainn Dec 03 '18 at 12:05
  • have a look at [`ctype_alpha()`](http://php.net/manual/en/function.ctype-alpha.php) – Karsten Koop Dec 03 '18 at 12:07
  • Strings in PHP can work like arrays. So you can do $username[0] ($username being 'hello') and it would have 'h'. So with this you can check if the first character is a valid character (A-Z). – paskl Dec 03 '18 at 20:01

1 Answers1

1

Below code is working fine.....

    $alphas = array_merge(range('a', 'z'), range('A', 'Z'));

    $errors=array();
    $username="username";
    echo $username[0];
    if (empty($username)){
        array_push($errors, "*Username cannot be blank<br>");
    }else if(!preg_match("/^[a-zA-Z0-9_]*$/",$username)){
        array_push($errors, "*Username can only contain alpha-numeric characters or an underscore<br>");
    }else if(!in_array($username[0],$alphas)){
        array_push($errors, "*Username must begin with a letter<br>");
    }else{
         echo "correct username";
// do what ever you want to code but do not hurt you mother :) :)
         die;
    }

    print_r($errors);
pawansgi92
  • 1,065
  • 13
  • 32