我对此完全感到困惑(或者我刚刚盯着它看了很长时间,以至于有一个明显的错误,我看不到它)
我有一个简单的表单,它在同一页面上验证,这是我制作的自定义模板
<form action="" method="post">
<input type="text" id="name" name="name" placeholder="Please enter your full name" />
<input type="email" id="email" name="email" placeholder="Please enter your email address" />
<input type="hidden" name="newsletterform" value="newsletterform" />
<input class="submit" type="submit" name="submit" id="searchsubmit" value="submit" />
</form>
然后验证如此
<?php
$formsubmitted = (!empty($_POST['newsletterform'])) ? $_POST['newsletterform'] : "";
if($formsubmitted !== ''){
$fullname = (!empty($_POST['name'])) ? $_POST['name'] : "";
$email = (!empty($_POST['email'])) ? $_POST['email'] : "";
$failed = '';
if (empty($fullname)){
$failed.= 'Please enter your name.<br />';
}
if (empty($email)){
$failed.= 'Please enter your email address.<br />';
}
}
if ($failed == '' and $formsubmitted !== ''){ ?>
<div id="success-title">
Thank you for signing up!
</div>
<?php
}
if ($failed !== '' and $formsubmitted !== '') { ?>
<div id="error-title">
Sorry, we could not accept the details you submitted to us. Please see below.
</div>
<div id="error-body">
<?php echo $failed;?>
</div>
<?php } ?>
它会在您尝试发送空表单时显示错误,当存在值且名称字段为空时,它会验证电子邮件是否正常。当某些内容输入到名称字段时,如果电子邮件字段中有内容或任何内容,则会转到我的404页面。
答案 0 :(得分:2)
解决方案非常简单,避免在表单中使用名为“name”的name
属性。
变化:
<input type="text" id="name" name="name" placeholder="Please enter your full name" />
为:
<input type="text" id="name" name="myname" placeholder="Please enter your full name" />
其他信息:
答案 1 :(得分:0)
对我而言,它以这种方式工作正常,请尝试用以下代码替换PHP:
<?php
$failed = '';
$formsubmitted = (!empty($_POST['newsletterform'])) ? $_POST['newsletterform'] : "";
if($formsubmitted !== ''){
$fullname = (!empty($_POST['name'])) ? $_POST['name'] : "";
$email = (!empty($_POST['email'])) ? $_POST['email'] : "";
if (empty($fullname)){
$failed.= 'Please enter your name.<br />';
}
if (empty($email)){
$failed.= 'Please enter your email address.<br />';
}
}
if ($failed == '' and $formsubmitted !== ''){
echo '<div id="success-title">
Thank you for signing up!
</div>';
}
if ($failed !== '' and $formsubmitted !== '') {
echo '<div id="error-title">
Sorry, we could not accept the details you submitted to us. Please see below.
</div>
<div id="error-body">';
echo $failed;
echo '</div>';
}
?>
答案 2 :(得分:0)
你可以这样做 -
<?php
if (strlen($fullname) < 3) {
// name too short, add error
$errors['name_error'] = 'Your name is required';
}elseif(strlen($fullname) ==0){
$errors['name_error'] = 'Your name is required';
}
if (strlen($email) == 0) {
// no email address given
$errors['email_error'] = 'Email address is required';
} else if ( !preg_match('/^(?:[\w\d]+\.?)+@(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/i', $email)) {
// invalid email format
$errors['email_error'] = 'Email address entered is invalid';
}
if (sizeof($errors) == 0) {
echo '<div id="success-title">
Thank you for signing up!
</div>';
}
else {
echo 'Sorry, we could not accept the details you submitted to us. Please see below.' . $errors;
}
?>