簡體   English   中英

聯系人表單無法在引導模態中驗證

[英]Contact form doesn't validate inside bootstrap modal

因此,我使用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;
        }
    })
});

將您的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
     }

 });

 });

Ondrej是Bootstrapious教程的作者。

我剛剛發現,Bootstrap驗證程序中存在錯誤,並且無法與Bootstrap模態結合使用。

解決方案是從https://github.com/1000hz/bootstrap-validator (當前為0.11.5)下載最新版本。

最好,

翁德里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM