【问题标题】:Contact form doesn't validate inside bootstrap modal联系表格在引导模式内无效
【发布时间】:2016-10-21 15:01:41
【问题描述】:

所以我使用https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form 的示例制作了一个联系表单,该表单在放置在页面上时可以正常工作,但是当我将其放置在引导弹出模式中时,验证器不起作用。如果所有字段都为空并点击提交按钮,即使没有发送,它也会说“消息已发送”,如果您填写字段,它仍然会发送并给出成功消息。

另外,如果我在页面加载后但在脚本加载之前点击按钮打开模式,它将起作用,所以这显然是因为在验证器脚本加载时模式不可见,所以它错过了它。

如果有人有一些答案,那将非常有帮助,因为我对 PHP 和 JS 还很陌生!

这是我的模态 HTML

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header"><button aria-label="Close" class="close"
data-dismiss="modal" type="button"><span aria-hidden=
"true">&times;</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form action="../contact.php" id="contact-form" method="post" name=
"contact-form">
<div class="messages"></div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_name">Firstname *</label>
<input class="form-control" data-error="Firstname is required." id="form_name"
name="name" placeholder="Please enter your first name" required="required"
type="text">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_email">Email *</label> <input class=
"form-control" data-error="Valid email is required." id="form_email" name=
"vemail" placeholder="Please enter your email" required="required" type=
"email">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_message">Message *</label> 
<textarea class="form-control" data-error="Please,leave us a message." id=
"form_message" name="message" placeholder="Please enter your message" required=
"required" rows="4"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12"><input class="btn btn-success btn-send" type="submit"
value="Send message"></div>
</div>
</form>
</div>
</div>
<!-- /.modal-content --></div>
<!-- /.modal-dialog --></div>
<!-- /.modal -->
</body>
</html>

这是我的 PHP 文件

<?php

// configure

$from = '<mail@myemail.net>'; 
$sendTo = 'Demo contact form <mail@myemail.net>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'vemail' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';    

$email = ($_POST["vemail"]);
$subject2 = 'Thank you for contacting support.';
$msg = "Thank you for contacting Support. We have received your contact form and will be in contact as soon as possible";
$headers = 'Reply-To: mail@myemail.net' . "\r\n" ;    

// let's do the sending

try
{
    $emailText = "You have new message from contact form\n=============================\n";
       foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }

   mail($email, $subject2, $msg, $headers) && mail($sendTo, $subject, $emailText, "From: " . $from);

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');        
    echo $encoded;
}
else {
    echo $responseArray['message'];
}
 ?>

还有 JS

$(function () {

    $('#contact-form').validator();

    $('#contact-form').on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
            var url = "../contact.php";

            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                    if (messageAlert && messageText) {
                        $('#contact-form').find('.messages').html(alertBox);
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        }
    })
});

【问题讨论】:

标签: javascript php jquery html twitter-bootstrap


【解决方案1】:

将您的 ajax 调用放入验证过程并使用 submitHandler

@Sparky 的这个回答可能会节省你的时间https://stackoverflow.com/a/15625824/6952155

请参考此内容并根据您的代码进行编辑。

$(document).ready(function () {

 $("#contactform").validate({
     ignore: ":hidden",
     rules: {
         name: {
             required: true,
             minlength: 3
         },
         cognome: {
             required: true,
             minlength: 3
         },
         subject: {
             required: true
         },
         message: {
             required: true,
             minlength: 10
         }
     },
     submitHandler: function (form) {
         alert('valid form submission'); // for demo
         $.ajax({
             type: "POST",
             url: "formfiles/submit.php",
             data: $(form).serialize(),
             success: function () {
                 $(form).html("<div id='message'></div>");
                 $('#message').html("<h2>Your request is on the way!</h2>")
                     .append("<p>someone</p>")
                     .hide()
                     .fadeIn(1500, function () {
                     $('#message').append("<img id='checkmark' src='images/ok.png' />");
                 });
             }
         });
         return false; // required to block normal submit since you used ajax
     }

 });

 });

【讨论】:

    【解决方案2】:

    这里是 Ondrej,Bootstrapious 教程的作者。

    我刚刚发现 Bootstrap 验证器有一个错误,它无法与 Bootstrap 模态组合正常工作。

    解决办法是从https://github.com/1000hz/bootstrap-validator下载最新版本,目前是0.11.5。

    最好的,

    翁德瑞

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多