Files
superlink/api/common/validate.php
T

56 lines
1.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 格式校验(2026-08-09)
* 邮箱 / 国内手机号码 / 身份证号码 正则验证
*/
/** 国内手机号码:11 位,1 开头,第二位 3-9 */
function validatePhoneCN($v)
{
return (bool)preg_match('/^1[3-9]\d{9}$/', trim((string)$v));
}
/** 邮箱 */
function validateEmail($v)
{
return (bool)preg_match('/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/', trim((string)$v));
}
/** 身份证号码:15 位 或 18 位(末位可为 X/x) */
function validateIdCard($v)
{
return (bool)preg_match('/^\d{15}$|^\d{17}[\dXx]$/', trim((string)$v));
}
/**
* 统一格式校验:不合法时直接返回错误响应
* @param string $type phone|email|id_number
* @param string $value
* @param bool $allowEmpty 空值是否放行(默认 true:未填不校验)
*/
function checkFieldFormat($type, $value, $allowEmpty = true)
{
$value = trim((string)$value);
if ($value === '') {
return $allowEmpty;
}
switch ($type) {
case 'phone':
if (!validatePhoneCN($value)) {
Response::error('手机号码格式不正确(应为国内 11 位手机号,如 13812345678)', 400);
}
break;
case 'email':
if (!validateEmail($value)) {
Response::error('邮箱格式不正确', 400);
}
break;
case 'id_number':
if (!validateIdCard($value)) {
Response::error('身份证号码格式不正确(应为 15 或 18 位)', 400);
}
break;
}
return true;
}