0

我在联系页面上有 HTML 表单字段,然后将数据发送到 php 页面。

如果用户没有输入值,我想让表单字段成为必填字段并在标签旁边显示一个红色 (*)。

我怎样才能做到这一点?

<form id="contact_form" method="post" action="contact.php">

    <p style="margin-top:20px">
        <label for="title">Title</label><br/>
        <input id="your_name" name="your_name" type="text" style="width:94%"/>
    </p>

    <p style="margin-top:20px">
        <label for="initial">Initial</label><br/>
        <input id="initial" name="initial" type="text" style="width:94%"/>
    </p>
    <p style="margin-top:20px">
        <label for="surname">Surname</label><br/>
        <input id="surname" name="surname" type="text" style="width:94%"/>
    </p>
        <p style="margin-top:20px">
        <label for="tel_number">Tel number</label><br/>
        <input id="tel_number" name="tel_number" type="text" style="width:94%"/>
    </p>
    <p style="margin-top:20px">
        <label for="email">Email</label><br/>
        <input id="email" name="email" type="text" style="width:94%"/>
    </p>

    <p style="margin-top:20px">
        <label for="enquiry">Enquiry</label><br/>
        <textarea id="enquiry" name="enquiry" rows="7" cols="10" style="width:94%"></textarea>
    </p>

    <p style="margin-top:50px">
        <input type="submit" value="Send Message"/><br/>
    </p>

</form>
4

1 回答 1

0

您必须将表单放入 php 文件(或.phtml推荐的*)中。添加一个 CSS 类,如.input-error.

.input-error { color: red; }

在您的表单中,每个字段都需要这样的内容:

if (empty($postData['field']) {
    echo "<span class=\"input-error\">*</span>";
}

举一个明确的例子:

<p style="margin-top:20px">
    <?php if (empty($postData['your_name']): ?>
        <span class="input-error">*</span>
    <?php endif; ?>
    <label for="title">Title</label><br/>
    <input id="your_name" name="your_name" type="text" style="width:94%"/>
</p>

表单必须提交到一个 php 文件,该文件将处理表单并将您带回此页面。在该文件中,您需要这样的一行:

$postData = $_POST;

或者,如果该脚本重定向到另一个页面,那么您需要将发布数据存储在会话中。喜欢:

$_SESSION['postData'] = $_POST;

在这种情况下,在表单顶部或控制器中的某个位置(如果有),像这样检索该数据:

$postData = $_SESSION['postData'];
于 2011-11-14T10:50:04.510 回答