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

PHP表单添加电话验证无效问题求助

PHP表单电话验证失效问题解决

问题描述

使用开源PHP表单代码添加电话验证功能时,模仿邮箱验证逻辑修改preg_match规则,支持数字、空格、括号和连字符,但提交表单时任意文本都能通过验证,无法触发预设的错误提示,复用邮箱验证代码也无效。

问题代码

<?php

// Set email variables
$email_to = 'anyemail@email.com';
$email_subject = 'New email from form';

// Set required fields
$required_fields = array('firstName','lastName','telephone','email','comment');

// set error messages
$error_messages = array(
    'firstName' => 'Please enter your first name to proceed.',
    'lastName' => 'Please enter your last name to proceed.',
    'email' => 'Please enter a valid email address to proceed.',
    'telephone' => 'Please enter a valid telephone number to proceed.',
    'comment' => 'Please enter your Message to continue.'
);

// Set form status
$form_complete = FALSE;

// configure validation array
$validation = array();

// check form submittal
if(!empty($_POST)) {
    // Sanitise POST array
    foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
    
    // Loop into required fields and make sure they match our needs
    foreach($required_fields as $field) {       
        // the field has been submitted?
        if(!array_key_exists($field, $_POST)) array_push($validation, $field);
        
        // check there is information in the field?
        if($_POST[$field] == '') array_push($validation, $field);
        
        // validate the email address supplied
        if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
        
        // validate the telephone supplied
        if($field == 'telephone') if(!validate_telephone($_POST[$field])) array_push($validation, $field);
    }
    
    // basic validation result
    if(count($validation) == 0) {
        // Prepare our content string
        $email_content = 'New Website Comment: ' . "\n\n";
        
        // simple email content
        foreach($_POST as $key => $value) {
            if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
        }
        
        // simple telephone content
        foreach($_POST as $key => $value) {
            if($key != 'submit') $telephone_content .= $key . ':' . $value . "/n";
        }
                
        // if validation passed ok then send the email
        mail($email_to, $email_subject, $email_content);
        
        // Update form switch
        $form_complete = TRUE;
    }
}

function validate_email_address($email = FALSE) {
    return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}

function remove_email_injection($field = FALSE) {
   return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}

function validate_telephone($telephone = FALSE) {
    return (preg_match('/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/', $telephone))? TRUE : FALSE;
}

?>

问题分析

  1. 正则表达式局限性:当前validate_telephone函数中的正则仅匹配北美格式的10位电话(如(123)456-7890),若输入其他格式会直接判定无效;如果用户尝试的正则存在语法错误(比如把\(?写成(?(),会导致preg_match返回false,函数错误返回FALSE但未被正确处理。
  2. 验证逻辑冗余:当前代码会对同一个字段多次添加到$validation数组(比如字段为空时添加一次,验证失败时再添加一次),虽不影响最终判断,但可能导致错误提示重复。

解决方案

方案1:修复正则表达式,支持多格式并严格验证

修改validate_telephone函数,先清理非数字字符检查长度,再验证原始格式仅包含允许的字符:

function validate_telephone($telephone = FALSE) {
    if(empty($telephone)) return FALSE;
    // 清理所有非数字字符,检查长度是否在7-15位(覆盖大部分国家号码长度)
    $cleaned_num = preg_replace('/\D/', '', $telephone);
    if(strlen($cleaned_num) < 7 || strlen($cleaned_num) > 15) {
        return FALSE;
    }
    // 验证原始输入仅包含数字、空格、括号、连字符
    return preg_match('/^[\d\s\-\(\)]+$/', $telephone) ? TRUE : FALSE;
}

方案2:优化验证逻辑,避免重复添加错误字段

修改循环中的电话验证部分,确保同一字段仅被添加一次到错误数组:

// validate the telephone supplied
if($field == 'telephone') {
    if(!validate_telephone($_POST[$field]) && !in_array($field, $validation)) {
        array_push($validation, $field);
    }
}

方案3:调试验证函数,定位问题

在validate_telephone函数中添加调试输出,查看匹配结果:

function validate_telephone($telephone = FALSE) {
    $match_result = preg_match('/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/', $telephone);
    // 调试输出,上线前删除
    echo "输入内容:{$telephone},匹配结果:{$match_result}<br>";
    return $match_result ? TRUE : FALSE;
}

通过调试输出可以直观看到输入内容是否符合正则规则,快速定位问题所在。

内容的提问来源于stack exchange,提问作者goldswoj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:05:26