Я обыскал весь Интернет, пытаясь найти решение того, чего мне здесь не хватает (или что я делаю неправильно). Моя форма не проверяется, даже если установлен флажок. Все остальное работает нормально.
Это тот флажок, я не могу нормально работать.
Я пробовал много разных идей, но это не подтверждается даже при проверке «условий» (например, в этом примере ниже).
Вот мой HTML:
<div class = "form-check">
<input type = "checkbox" class = "form-check-input" name = "terms" id = "terms" />
<label class = "form-check-label" for = "terms"><p>I agree to terms of service.</p></label>
</div>
Вот вся моя проверка PHP (обновленная комментариями / ответами ниже):
<?php
if (!$_POST) exit;
// Email address verification.
function isEmail($email) { // lots of email validation stuff in here // }
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$terms = $_POST['terms'];
//set an error counter to trigger the `exit`
$error_counter = 0;
if (trim($name) == '') {
echo '<div class = "error_message">Attention! You must enter your name</div>';
$error_counter++;
}
if (trim($email) == '') {
echo '<div class = "error_message">Attention! Please enter a valid email
address.</div>';
$error_counter++;
}
if (!isEmail($email)) {
echo '<div class = "error_message">Attention! You have entered an invalid e-
mail address, try again.</div>';
$error_counter++;
}
if (trim($subject) == '') {
echo '<div class = "error_message">Attention! Please enter a subject.</div>';
$error_counter++;
}
if (trim($comments) == '') {
echo '<div class = "error_message">Attention! Please enter your message.
</div>';
$error_counter++;
}
if (empty($terms)) {
echo '<div class = "error_message">Attention! Please agree to our terms of
service.</div>';
$error_counter++;
}
//if `$error_counter > 0 > 0` it will trigger the `exit()` to stop the script and display the errors.
if ($error_counter > 0){
exit();
}
if (get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "[email protected]";
$address = "[email protected]";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You have been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name with regards to $subject, their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email ";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if (mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>






Вы не устанавливаете какой-либо атрибут значения для своего флажка:
<input type = "checkbox" class = "form-check-input" name = "terms" id = "terms" value = "yes" />
Дополнительная информация: https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/checkbox
Браузеры обычно присваивают ему значение по умолчанию (например, «включено»), если атрибут значения не установлен. stackoverflow.com/questions/12911787/…
Я пробовал с атрибутом value и без него. Те же проблемы.
Я вижу, что ваш флажок не имеет значения, поэтому часть PHP получает мусор / пустое значение.
Короче говоря, просто добавьте атрибут required в свою HTML-сторону. Нет необходимости в проверке на стороне сервера
<div class = "form-check">
<input type = "checkbox" class = "form-check-input" name = "terms" id = "terms" required/>
<label class = "form-check-label" for = "terms"><p>I agree to terms of service.</p></label>
</div>
Я пробовал это со значением = "true" в HTML. И я изменил проверку на if (($ terms)! = 'True') {etc ....}, но она по-прежнему работает некорректно.
«required» работает нормально, но я надеялся выяснить, что я делаю не так.
Проблема с вашей текущей проверкой заключается в том, что вы неправильно используете if-else и что вы используете exit для каждого оператора, который преждевременно завершает ваш скрипт.
Вместо этого вы можете сделать это:
For Terms:
<input type = "checkbox" class = "form-check-input" name = "terms" id = "terms" value = "1"/>
//set an error counter to trigger the `exit`
$error_counter = 0;
if (trim($name) == '') {
echo '<div class = "error_message">Attention! You must enter your name</div>';
$error_counter++;
}
if (trim($email) == '') {
echo '<div class = "error_message">Attention! Please enter a valid email
address.</div>';
$error_counter++;
}
if (!isEmail($email)) {
echo '<div class = "error_message">Attention! You have entered an invalid e-
mail address, try again.</div>';
$error_counter++;
}
if (trim($subject) == '') {
echo '<div class = "error_message">Attention! Please enter a subject.</div>';
$error_counter++;
}
if (trim($comments) == '') {
echo '<div class = "error_message">Attention! Please enter your message.</div>';
$error_counter++;
}
if (empty($terms)) {
echo '<div class = "error_message">Attention! Please agree to our terms of service.</div>';
$error_counter++;
}
//if `$error_counter > 0 > 0` it will trigger the `exit()` to stop the script and display the errors.
if ($error_counter > 0){
exit();
}
Есть более красивый подход к этому. Не стесняйтесь добавлять предложения для OP.
Спасибо. Но ... флажок по-прежнему не проверяет "истину", даже если флажок установлен. Я обновил свой вопрос, включая весь PHP с конфигурациями электронной почты. Может быть, там есть что-то еще, чего мне не хватает.
Я решил установить значение для вашего флажка, так как это хорошая практика никогда не позволять этому зависать без значений. Вы можете попробовать это вместо
Ваша проверка закончится в тот момент, когда вернет true. Также стоит отметить, что вы
exitвсе операторы if-else. Вместо этого вам следует создать отдельные операторы if-else для проверки их валидации.