表单问题的PHP验证

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (141)

我整天都在进行这种表格验证,我几乎就在那里,但它还不对。有人告诉我在w3schools使用这个例子我做了但它没有用。我搞砸了一段时间,现在它确实有效,但有些事情仍然搞砸了。如果有超过1个错误,则不会显示。只显示最后一个出现。其次,我希望它通过页面上的输入显示错误。目前它是一个空白页面,只是回应错误。我尝试将它们包含在表单的html中,但它不起作用。我使用的例子是:

https://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_complete

我的代码如下

HTML:

   <form class="form inline d-flex justify-content-center" action="contact.php" method="POST" role="form">
             <br style="clear:both">
            <div class="col-sm-6">
              <div class="form-group">
                <input type="text" class="control" id="first_name" name="first_name" placeholder="First Name" required>
                <span class="error">* <?php echo $nameErr;?></span>
              </div>
              <div class="form-group">
                <input type="text" class="control" id="email" name="email" placeholder="Email" required>
                <span class="error">* <?php echo $emailErr;?></span>
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <input type="text" class="control" id="last_name" name="last_name" placeholder="Last Name" required>
                <span class="error">* <?php echo $nameErr;?></span>
              </div>
              <div class="form-group">
                <input type="text" class="control" id="phone" name="phone" placeholder="Phone" required>
                <span class="error">* <?php echo $phoneErr;?></span>
              </div>
            </div>
            <div class="col-sm-12">
              <div class="form-group">
                <textarea name="message" class="control" id="message" placeholder="What's on your mind?" rows="3"></textarea>
              </div>
              <button type="submit" id="submit" name="submit" class="btn btn-primary">SEND</button>
          </form>

PHP:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $first_name = $_POST['first_name'];
    $last_name  = $_POST['last_name'];
    $email      = $_POST['email'];
    $phone      = $_POST['phone'];
    $message    = $_POST['message'];

    if (empty($first_name)) {
        $nameErr = "First name is required";
    } else {
        $first_name = check_input($first_name);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
            $error = "Only letters and white space allowed";
        } else {
            $pass += 1;
        }
    }

    if (empty($last_name)) {
        $nameErr = "Last name is required";
    } else {
        $last_name = check_input($last_name);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$last_name)) {
            $error = "Only letters and white space allowed";
        }else {
            $pass += 1;
        }
    }

    if (empty($email)) {
        $emailErr = "Email is required";
    } else {
        $email = check_input($email);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = "Invalid email format";
        }else {
            $pass += 1;
        }
    }

    if (empty($phone)) {
        $phoneErr = "Phone number is required";
    } else {
        $phone = check_input($phone);

        if (!preg_match("'^(([\+]([\d]{2,}))([0-9\.\-\/\s]{5,})|([0-9\.\-\/\s]{5,}))*$'",$phone)) {
            $error = "Invalid Phone Number";
        }else {
            $pass += 1;
        }
    }

    if (empty($message)) {
        $error = "Message  cannot be blank";
    } else {
        $message = check_input($message);
        $pass += 1;
    }
}

$email_from =' Client, llc';
$email_subject = 'New Message From A Guest';
$email_body = "Name: $first_name $last_name\n".
              "Email: $email\n".
              "Phone: $phone\n".
              "Message: $message.\n";
$to ="me@work.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";

if (!isset($error) && $pass == '5'){
    mail($to,$email_subject,$email_body,$headers);
    header("location: thanks.html");
} else {
    echo $error;
}

// purge the session after it is displayed
unset($error);

function check_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

我不认为电话检查工作正常,但我可以尝试不同的preg_match。我只需要让它正常工作。

提问于
用户回答回答于

每次发生错误时,您都会覆盖$ error中的值。您需要将新错误消息附加到现有错误。此外,如果您希望在输入旁边显示错误消息,则需要将错误消息放在相应的错误变量中。

更新html中姓氏错误的ID:

 <form class="form inline d-flex justify-content-center" action="contact.php" method="POST" role="form">
             <br style="clear:both">
            <div class="col-sm-6">
              <div class="form-group">
                <input type="text" class="control" id="first_name" name="first_name" placeholder="First Name" required>
                <span class="error">* <?php echo $nameErr;?></span>
              </div>
              <div class="form-group">
                <input type="text" class="control" id="email" name="email" placeholder="Email" required>
                <span class="error">* <?php echo $emailErr;?></span>
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <input type="text" class="control" id="last_name" name="last_name" placeholder="Last Name" required>
                <span class="error">* <?php echo $nameErr2;?></span>
              </div>
              <div class="form-group">
                <input type="text" class="control" id="phone" name="phone" placeholder="Phone" required>
                <span class="error">* <?php echo $phoneErr;?></span>
              </div>
            </div>
            <div class="col-sm-12">
              <div class="form-group">
                <textarea name="message" class="control" id="message" placeholder="What's on your mind?" rows="3"></textarea>
              </div>
              <button type="submit" id="submit" name="submit" class="btn btn-primary">SEND</button>
          </form>

试试这个PHP:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $first_name = $_POST['first_name'];
    $last_name  = $_POST['last_name'];
    $email      = $_POST['email'];
    $phone      = $_POST['phone'];
    $message    = $_POST['message'];
    $error = ''; //init error to empty string
    $pass = 0; // init pass to 0;

    if (empty($first_name)) {
        $nameErr = "First name is required";
    } else {
        $first_name = check_input($first_name);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
            $nameErr = "Only letters and white space allowed";
            $error.='<p>'.$nameErr.'</p>';

        } else {
            $pass += 1;
        }
    }

    if (empty($last_name)) {
        $nameErr2 = "Last name is required";
    } else {
        $last_name = check_input($last_name);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$last_name)) {
            $nameErr2 = "Only letters and white space allowed";
            $error.='<p>'.$nameErr2.'</p>';
        }else {
            $pass += 1;
        }
    }

    if (empty($email)) {
        $emailErr = "Email is required";
    } else {
        $email = check_input($email);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
            $error.='<p>'.$emailErr.'</p>';
        }else {
            $pass += 1;
        }
    }

    if (empty($phone)) {
        $phoneErr = "Phone number is required";
    } else {
        $phone = check_input($phone);

        if (!preg_match("'^(([\+]([\d]{2,}))([0-9\.\-\/\s]{5,})|([0-9\.\-\/\s]{5,}))*$'",$phone)) {
            $phoneErr = "Invalid Phone Number";
            $error.='<p>'.$phoneErr.'</p>';
        }else {
            $pass += 1;
        }
    }

    if (empty($message)) {
        $msgErr = "Message  cannot be blank";
        $error.='<p>'.$msgErr.'</p>';
    } else {
        $message = check_input($message);
        $pass += 1;
    }
}

$email_from =' Client, llc';
$email_subject = 'New Message From A Guest';
$email_body = "Name: $first_name $last_name\n".
              "Email: $email\n".
              "Phone: $phone\n".
              "Message: $message.\n";
$to ="me@work.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";

if ($error == '' && $pass == '5'){
    mail($to,$email_subject,$email_body,$headers);
    header("location: thanks.html");
} else {
    echo $error;
}

// purge the session after it is displayed
unset($error);

function check_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

热门问答

拯救小助理大作战1: 云+的活动由你来决定!?

青年码农

晨讯科技 · web前端开发高级工程师 (已认证)

公众号【青年码农】:有趣、有料,有深度、有广度、有热度。
活动形式 对于云的实际操作,之前关于云的基本都是文章、视频等形式来对技术的阐述,对于使用云的开发者来说,可能意义不大,而希望的是实际操作,毕竟实际操作遇到的问题才是真正要解决的问题 活动大纲(例) 主题:使用云开发搭建一个小程序或者提供一个后台接口 腾讯云提供了n多个服务,多数服...... 展开详请

实时音视频如何实现画中画的效果?

Cstar

腾讯 · 产品经理 (已认证)

推荐
开启大小画面双路编码模式的接口如下: iOS&Mac:enableEncSmallVideoStream Android:enableEncSmallVideoStream Windows(C++):enableSmallVideoStream Windows(C#):enab...... 展开详请

有没有可以提升运维效率的服务器管理软件,主要功能有哪些,求推荐?

The parameter `SecretKey` is not recognized?

zqfan

腾讯 · 高级工程师 (已认证)

推荐已采纳

报错的意思是参数SecretKey无法识别,接口实际未定义这个字段。

SecretKey是你的密钥,相当于你的账户密码,调用API时是不需要传递的。

桌面浏览器版和安卓版能进入一个实时音视频房间么?

人生的旅途辣鸡前端
推荐已采纳
https://cloud.tencent.com/document/product/647/43019 image.png ... 展开详请

智聆口语评测返回结果里面的评分为0?

1,音频文件要符合16khz采样率16bit位深单声道,如果是mp3文件码率要高于48kbps,否则评分可能会出现偏低或者0 2,VoiceType是否和传入的音频文件一致,文本和音频是否一致. 3,看下sessionId是否在每次评测的时候都是一样的结果导致的   4,在初次...... 展开详请

所属标签

扫码关注云+社区

领取腾讯云代金券