Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP bug while validating user name

I'm building a website using PHP and I need to validate whether the name entered by the user is correct or not. Since JavaScript is client-side, I cannot completely rely on that, so here's my server-side function to validate the name of the user:

function validate_name($name) {
    $name = trim($name);  // only for the purpose of debugging <---- edited comment
    echo $name;
    if (strlen($name) <= 1) {
        return "small";
    } else if (has_numbers($name)) { 
        return "numbers";
    } else {
        return true;
    }
}

After this, I check the input and display result accordingly:

function final_check() {
    if (validate_name($_POST["first_name"]) == "small") {
        echo "<span class='error'>Your first name cannot be empty</span>";
        return false;
    } else if (validate_name($_POST["first_name"]) == "numbers") {
        echo "<span class='error'>Numbers are not allowed in your first name</span>";
        return false;
    }
    return true;
}

When I enter nothing in the first_name field, I get the empty error message; when I enter numbers, I get the numbers error message. However, when I do enter a valid name, it gives me the name empty error message.

Here's the post data:

Array
(
    [email] => [email protected]
    [first_name] => qwe
    [last_name] => wqe
    [password] => qwe
    [re_password] => qwe
    [gender] => Male
)

Output:

Your first name cannot be empty

Any idea what I am doing wrong? I have been stumped for the past hour trying to fix this and I haven't been able to find a solution.

like image 979
Always Learning Forever Avatar asked Jul 17 '26 02:07

Always Learning Forever


1 Answers

Array
(
    [email] => [email protected]
    [first_name] => qwe
    [last_name] => wqe
    [password] => qwe
    [re_password] => qwe
    [gender] => Male
)

// First_name length = 3

function validate_name($name) {
    $name = trim($name);
    echo $name;
    if (strlen($name) <= 1) {
        return "small";
    } else if (has_numbers($name)) { 
        return "numbers";
    } else {
        return true;      // satisfy this case return true
    }
}

and here it's becoming like

function final_check() {
    if (validate_name($_POST["first_name"]) == "small") {   // if(1 == 'small')
        echo "<span class='error'>Your first name cannot be empty</span>";
        return false;
    } else if (validate_name($_POST["first_name"]) == "numbers") {
        echo "<span class='error'>Numbers are not allowed in your first name</span>";
        return false;
    }
    return true;
}

if(1 == 'small') its a string comparison with Boolean which always going to return true.

Please check this page in the manual to understand the problem.

like image 170
Naincy Avatar answered Jul 19 '26 23:07

Naincy