You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP编写函数验证HTML表单中的姓名?

PHP表单姓名验证实现指南

一、确定姓名验证规则

常用的合理规则(可根据需求调整):

  • 不能为空(即使HTML有required,后端也要二次验证,防止前端绕过)
  • 只能包含字母、空格、单引号(')、连字符(-)、句点(.)(覆盖大多数姓名格式)
  • 长度限制:最少2个字符,最多50个字符

二、修改PHP代码添加验证逻辑

在教授提供的代码中,在sanitize输入之前添加验证步骤,收集错误信息;如果有错误则不执行保存逻辑,返回表单页面显示错误。修改后的完整代码示例:

<?php
session_start(); // 确保开启会话,因为用到了$_SESSION

$errors = []; // 存储验证错误信息

if(isset($_POST['save'])){
    // 验证名字(firstname)
    if(empty($_POST['fn'])){
        $errors[] = "名字不能为空";
    } elseif(!preg_match('/^[a-zA-Z\'\-\s.]+$/', trim($_POST['fn']))){
        $errors[] = "名字只能包含字母、空格、单引号、连字符或句点";
    } elseif(strlen(trim($_POST['fn'])) < 2 || strlen(trim($_POST['fn'])) > 50){
        $errors[] = "名字长度需在2-50个字符之间";
    }

    // 验证姓氏(lastname),规则与名字一致
    if(empty($_POST['ln'])){
        $errors[] = "姓氏不能为空";
    } elseif(!preg_match('/^[a-zA-Z\'\-\s.]+$/', trim($_POST['ln']))){
        $errors[] = "姓氏只能包含字母、空格、单引号、连字符或句点";
    } elseif(strlen(trim($_POST['ln'])) < 2 || strlen(trim($_POST['ln'])) > 50){
        $errors[] = "姓氏长度需在2-50个字符之间";
    }

    // 无错误时执行sanitize和保存逻辑
    if(empty($errors)){
        // sanitize user inputs
        $firstname = htmlentities(trim($_POST['fn']));
        $lastname = htmlentities(trim($_POST['ln']));
        $email = htmlentities($_POST['email']);
        $status = 'Inactive';
        if(isset($_POST['status'])){
            $status = $_POST['status'];
        }
        $faculty = array(
            "firstname" => $firstname,
            "lastname" => $lastname,
            "email" => $email,
            "academic_rank" => $_POST['rank'],
            "department" => $_POST['department'],
            "admission_role" => $_POST['role'],
            "status" => $status
        );
        // 确保$_SESSION['faculty']存在,避免报错
        if(!isset($_SESSION['faculty'])){
            $_SESSION['faculty'] = [];
        }
        array_push($_SESSION['faculty'], $faculty);

        //redirect user to faculty page after saving
        header('location: faculty.php');
        exit; // 跳转后必须终止代码执行,避免后续操作
    }
}
?>

三、在HTML表单中显示错误信息

在表单顶部添加错误提示区域,同时保留用户已输入的内容,提升体验:

<!-- 错误提示区域 -->
<?php if(!empty($errors)): ?>
    <div style="color: red; margin-bottom: 10px;">
        <?php foreach($errors as $error): ?>
            <p><?php echo $error; ?></p>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<!-- 原表单代码(补充姓氏输入框及回显逻辑) -->
<label for="fn">First Name</label>
<input type="text" id="fn" name="fn" required placeholder="Enter first name" value="<?php echo isset($_POST['fn']) ? htmlentities($_POST['fn']) : ''; ?>">

<label for="ln">Last Name</label>
<input type="text" id="ln" name="ln" required placeholder="Enter last name" value="<?php echo isset($_POST['ln']) ? htmlentities($_POST['ln']) : ''; ?>">

<input type="submit" class="button" value="Save Faculty" name="save" id="save">

四、关键知识点说明

  • 后端验证必要性:前端required可通过浏览器控制台修改绕过,必须在后端做二次验证。
  • 正则表达式/^[a-zA-Z\'\-\s.]+$/:限定输入仅允许大小写字母、单引号、连字符、空格、句点,覆盖绝大多数合法姓名格式。
  • trim()函数:去除输入内容前后的空格,避免用户输入纯空格的无效内容。
  • htmlentities():转义特殊字符,防止XSS攻击,同时避免HTML渲染异常。
  • 跳转后exit:确保跳转后终止代码执行,避免不必要的后续操作。

内容的提问来源于stack exchange,提问作者Bin-baz Akilan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 05:15:39