我一直在为注册表单创建一些验证,但在验证用户名时遇到错误。
我对名字和姓氏都使用了“测试”的输入,但在应该允许输入时仍然出现错误,因为!preg_match('/^[a-z]*$/i', $value)
应该允许小写和大写字符?
此外,我得到的错误似乎只触发名字而不是姓氏。
<?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;
}
}
}
?>
最佳答案
您在“OR”条件周围缺少括号。 “AND”优先于“OR”。
if(($field === 'firstname' || $field === 'lastname') && !preg_match('/^[a-z]*$/i', $value)){
$errors[] = "{$field} has invalid characters please try again.";
}
注意:在上面的代码中,您有一个“ undefined variable ”:
$error
.
关于PHP 名称验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48711226/