本文目录导读:

在PHP中处理验证失败并返回自定义响应,常见有以下几种方式:
使用原生PHP(基础方式)
<?php
// 验证函数
function validateInput($data) {
$errors = [];
// 验证用户名
if (empty($data['username'])) {
$errors[] = '用户名不能为空';
} elseif (strlen($data['username']) < 3) {
$errors[] = '用户名至少3个字符';
}
// 验证邮箱
if (empty($data['email'])) {
$errors[] = '邮箱不能为空';
} elseif (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = '邮箱格式不正确';
}
// 验证密码
if (empty($data['password'])) {
$errors[] = '密码不能为空';
} elseif (strlen($data['password']) < 6) {
$errors[] = '密码至少6个字符';
}
return $errors;
}
// 使用示例
$input = $_POST;
$errors = validateInput($input);
if (!empty($errors)) {
// 自定义响应
$response = [
'success' => false,
'message' => '验证失败',
'errors' => $errors,
'timestamp' => time()
];
// 返回JSON格式
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
// 验证通过继续处理
echo json_encode(['success' => true, 'message' => '验证通过']);
?>
使用类封装(面向对象方式)
<?php
class Validator {
private $errors = [];
private $data;
public function __construct($data) {
$this->data = $data;
}
public function required($field, $label = '') {
if (empty($this->data[$field])) {
$this->errors[$field][] = ($label ?: $field) . '不能为空';
}
return $this;
}
public function email($field) {
if (!empty($this->data[$field]) && !filter_var($this->data[$field], FILTER_VALIDATE_EMAIL)) {
$this->errors[$field][] = '邮箱格式不正确';
}
return $this;
}
public function minLength($field, $min, $label = '') {
if (!empty($this->data[$field]) && strlen($this->data[$field]) < $min) {
$this->errors[$field][] = ($label ?: $field) . "至少{$min}个字符";
}
return $this;
}
public function maxLength($field, $max, $label = '') {
if (!empty($this->data[$field]) && strlen($this->data[$field]) > $max) {
$this->errors[$field][] = ($label ?: $field) . "不能超过{$max}个字符";
}
return $this;
}
public function validate() {
return empty($this->errors);
}
public function getErrors() {
return $this->errors;
}
public function getResponse() {
return [
'success' => false,
'message' => '验证失败',
'errors' => $this->errors,
'error_count' => count($this->errors),
'timestamp' => date('Y-m-d H:i:s')
];
}
}
// 使用示例
$validator = new Validator($_POST);
$validator->required('username', '用户名')
->minLength('username', 3, '用户名')
->required('email', '邮箱')
->email('email')
->required('password', '密码')
->minLength('password', 6, '密码');
if (!$validator->validate()) {
// 返回自定义JSON响应
header('Content-Type: application/json');
http_response_code(422); // Unprocessable Entity
echo json_encode($validator->getResponse());
exit;
}
echo json_encode(['success' => true, 'message' => '验证通过']);
?>
使用异常的验证方式
<?php
class ValidationException extends Exception {
private $errors;
public function __construct($errors, $message = "验证失败", $code = 422) {
parent::__construct($message, $code);
$this->errors = $errors;
}
public function getErrors() {
return $this->errors;
}
public function getJsonResponse() {
header('Content-Type: application/json');
http_response_code($this->getCode());
return json_encode([
'success' => false,
'message' => $this->getMessage(),
'errors' => $this->errors,
'error_code' => $this->getCode()
]);
}
}
function validateUserData($data) {
$errors = [];
// 验证规则
$rules = [
'username' => [
'required' => true,
'min' => 3,
'max' => 50,
'label' => '用户名'
],
'email' => [
'required' => true,
'email' => true,
'label' => '邮箱'
],
'password' => [
'required' => true,
'min' => 6,
'label' => '密码'
]
];
foreach ($rules as $field => $rule) {
$value = $data[$field] ?? '';
$label = $rule['label'];
if ($rule['required'] && empty($value)) {
$errors[$field][] = "{$label}不能为空";
continue;
}
if (!empty($value)) {
if (isset($rule['min']) && strlen($value) < $rule['min']) {
$errors[$field][] = "{$label}至少{$rule['min']}个字符";
}
if (isset($rule['max']) && strlen($value) > $rule['max']) {
$errors[$field][] = "{$label}不能超过{$rule['max']}个字符";
}
if (isset($rule['email']) && $rule['email'] && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
$errors[$field][] = "{$label}格式不正确";
}
}
}
if (!empty($errors)) {
throw new ValidationException($errors);
}
return true;
}
// 使用示例
try {
validateUserData($_POST);
// 验证通过,继续处理
echo json_encode(['success' => true, 'message' => '验证通过']);
} catch (ValidationException $e) {
echo $e->getJsonResponse();
exit;
}
?>
简洁的实用函数(适合API)
<?php
function validateRequest($rules, $data = null) {
$data = $data ?? $_POST;
$errors = [];
foreach ($rules as $field => $rule) {
$value = $data[$field] ?? null;
$label = $rule['label'] ?? $field;
// required
if (($rule['required'] ?? false) && ($value === null || $value === '')) {
$errors[$field][] = "{$label}不能为空";
continue;
}
if ($value !== null && $value !== '') {
// type validation
if (isset($rule['type'])) {
switch ($rule['type']) {
case 'email':
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$errors[$field][] = "{$label}格式不正确";
}
break;
case 'number':
if (!is_numeric($value)) {
$errors[$field][] = "{$label}必须是数字";
}
break;
case 'string':
if (!is_string($value)) {
$errors[$field][] = "{$label}必须是字符串";
}
break;
}
}
// min/max length
if (isset($rule['min']) && strlen($value) < $rule['min']) {
$errors[$field][] = "{$label}至少{$rule['min']}个字符";
}
if (isset($rule['max']) && strlen($value) > $rule['max']) {
$errors[$field][] = "{$label}不能超过{$rule['max']}个字符";
}
}
}
return $errors;
}
// 定义验证规则
$rules = [
'username' => [
'required' => true,
'min' => 3,
'max' => 50,
'label' => '用户名'
],
'email' => [
'required' => true,
'type' => 'email',
'label' => '邮箱'
],
'password' => [
'required' => true,
'min' => 6,
'label' => '密码'
]
];
// 验证并返回自定义响应
$errors = validateRequest($rules);
if (!empty($errors)) {
$response = [
'success' => false,
'message' => '请检查以下字段',
'errors' => $errors,
'error_fields' => array_keys($errors)
];
header('Content-Type: application/json');
http_response_code(422);
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;
}
// 验证通过
echo json_encode(['success' => true, 'message' => '验证通过']);
?>
建议的响应格式
{
"success": false,
"message": "验证失败",
"errors": {
"username": ["用户名不能为空", "用户名至少3个字符"],
"email": ["邮箱格式不正确"]
},
"error_count": 2,
"timestamp": "2024-01-01 12:00:00"
}
选择哪种方式取决于你的项目需求:
- 简单项目:使用原生PHP方式
- 复杂项目:使用类封装或异常方式
- API项目:使用简洁的实用函数方式