Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP name validation

I have been creating some validation for a signup form, and I have come across an error when validating the user's name.

I have used an input of "Test" for both firstname and lastname and I still get an error when it should allow the input, since !preg_match('/^[a-z]*$/i', $value) should allow both lower and uppercase characters?

Also the error that I get seems to be only triggering for the firstname and not last name.

<?php 
   if (isset($_POST['submit'])){
        require_once 'config.php';

        $errors = [];

        foreach($_POST as $field => $value){
            if($field === 'firstname' || $field === 'lastname' && !preg_match('/^[a-z]*$/i', $value)){
                $errors[] = "{$field} has invalid characters please try again.";
                echo $error;
            }         
        }
}
?>
like image 444
TessRay97 Avatar asked Oct 28 '25 16:10

TessRay97


1 Answers

You are missing brackets around your "OR" condition. The "AND" takes precedence over "OR".

if(($field === 'firstname' || $field === 'lastname') && !preg_match('/^[a-z]*$/i', $value)){
     $errors[] = "{$field} has invalid characters please try again.";
}

NB: In your code above, you have an "undefined variable" : $error.

like image 99
Syscall Avatar answered Oct 31 '25 07:10

Syscall