PHP form processing: form data verification and error prompts
<?php // 接收表单数据 $name = $_POST['name']; $email = $_POST['email']; $password = $_POST['password']; // 校验表单数据 $errors = []; if (empty($name)) { $errors['name'] = '姓名不能为空'; } if (empty($email)) { $errors['email'] = '邮箱不能为空'; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = '邮箱格式不正确'; } if (empty($password)) { $errors['password'] = '密码不能为空'; } elseif (strlen($password) < 6) { $errors['password'] = '密码长度不能少于6位'; } // 判断是否有错误 if (count($errors) > 0) { // 提示用户错误信息 foreach ($errors as $error) { echo $error . '<br>'; } } else { // 数据校验通过,可以进行下一步操作 // ... } ?>
<?php // 接收表单数据 $name = $_POST['name']; $email = $_POST['email']; $password = $_POST['password']; // 校验表单数据 $errors = []; if (empty($name)) { $errors['name'] = '姓名不能为空'; } if (empty($email)) { $errors['email'] = '邮箱不能为空'; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = '邮箱格式不正确'; } if (empty($password)) { $errors['password'] = '密码不能为空'; } elseif (strlen($password) < 6) { $errors['password'] = '密码长度不能少于6位'; } // 判断是否有错误 if (count($errors) > 0) { // 错误提示 echo '<ul>'; foreach ($errors as $error) { echo '<li>' . $error . '</li>'; } echo '</ul>'; ?> <script> // 使用JavaScript弹窗展示错误信息 alert('<?php echo implode(' ', $errors); ?>'); </script> <?php } else { // 数据校验通过,可以进行下一步操作 // ... } ?>
In the above code, we use an array $errors
to collect error information. When an error occurs, we use echo
or JavaScript pop-up window to prompt the error message to let the user know and correct the error.
The above is the relevant content about data verification and error prompts in PHP form processing. I hope it will be helpful to you!
The above is the detailed content of PHP form processing: form data verification and error prompts. For more information, please follow other related articles on the PHP Chinese website!