【问题标题】:jquery id causing error in form validationjquery id导致表单验证错误
【发布时间】:2016-07-15 22:38:24
【问题描述】:

我试图使联系表工作,但是当我删除 id="contactform" 验证不起作用但我得到成功消息,当我删除 id="contactform" 时验证不起作用。所以这是我的代码,php 代码工作正常,但 jquery 中存在一些问题

// Contact form
$(function() {
    // validate contact form on keyup and submit
    $("#contactForm").validate({
        rules: {
            name: {
                required: true,
                minlength: 2,
                lettersonly: true
            },
            email: {
                required: true,
                minlength: 6,
                email: true
            },
            phone: {
                required: true,
                digits: true,
                minlength: 10,
                maxlength: 15
            },
            message: {
                required: true,
                minlength: 6
            }
        },
        messages: {
            name: {
                required: "Please enter your name",
                minlength: "Minimum 2 characters",
                lettersonly: "Only letters please!"
            },
            email: {
                required: "Please enter your email address",
                minlength: "Minimum 6 characters",
                email: "That's an invalid email"
            },
            phone: {
                required: "Please enter your phone number",
                digits: "Only digits (no spaces)",
                minlength: "Minimum 10 characters",
                maxlength: "Maximum 15 characters"
            },
            message: {
                required: "Please enter your message",
                minlength: "Minimum 6 characters"
            }
        },
        success: function(label) {
            label.addClass("valid").text("Perfect!");
        },
        submitHandler: function(element) {

            var ajaxform = $(element),
                url = ajaxform.attr('action'),
                type = ajaxform.attr('method'),
                data = {};

            $(ajaxform).find('[name="submit"]').html('<i class="fa fa-circle-o-notch fa-spin fa-fw"></i> Sending...');


            ajaxform.find('[name]').each(function(index, value) {
                var field = $(this),
                    name = field.attr('name'),
                    value = field.val();

                data[name] = value;

            });

            $.ajax({
                url: url,
                type: type,
                data: data,
                success: function(response) {
                    if (response.type == 'success') {
                        $("#contactForm").before("<div class='alert alert-success' role='alert'><a href='#' class='close' data-dismiss='alert'>&times;</a>" + response.text + "</div>");
                        $(ajaxform).each(function() {
                            this.reset();
                            $(this).find('[name="submit"]').html('<i class="fa fa-paper-plane fa-fw"></i> Send');
                        }).find('.valid').each(function() {
                            $(this).remove('label.valid');
                        })
                    } else if (response.type == 'error') {
                        $("#contactForm").before("<div class='alert alert-danger' role='alert'><a href='#' class='close' data-dismiss='alert'>&times;</a>" + response.text + "</div>");
                        $(ajaxform).find('[name="submit"]').html('<i class="fa fa-paper-plane fa-fw"></i> Send');
                    }
                }
            });

            return false;
        }
    });

});


**and my HTML Code is:**

    <!--- Contact Section-->
    <!-- Contact section -->
    <
    section id = "contact"
class = "contact content-section no-bottom-pad wow fadeIn"
data - wow - offset = "10" >
    <
    div class = "container" >
    <
    div class = "row text-center" >
    <
    div class = "col-md-12" >
    <
    h2 > Contact < /h2> <
    h3 class = "caption gray" > Feel free to get in touch with us
if you have a new project or simply something awesome < /h3> <
    /div><!-- /.col - md - 12 -->

    <
    /div><!-- /.row-- >
    <
    /div><!-- /.container-- >

    <
    div class = "container" >
    <
    div class = "row form-container" >

    <
    div class = "col-md-8 contact-form" >
    <
    h3 > Drop us a line < /h3> <
    form class = "ajax-form"
id = "contactForm"
method = "post"
action = "assets/php/contact.php" >
    <
    div class = "form-group" >
    <
    input type = "text"
class = "form-control"
id = "name"
name = "name"
placeholder = "Your Name..."
value = ""
required >
    <
    /div> <
    div class = "form-group" >
    <
    input type = "email"
class = "form-control"
id = "email"
name = "email"
placeholder = "Your email..."
value = ""
required >
    <
    /div> <
    div class = "form-group" >
    <
    input type = "phone"
class = "form-control"
id = "phone"
name = "phone"
placeholder = "Your phone..."
value = ""
required >
    <
    /div> <
    div class = "form-group" >
    <
    textarea class = "form-control"
rows = "4"
name = "message"
placeholder = "Your message..."
required > < /textarea> <
    /div> <
    div class = "form-group" >
    <
    button type = "submit"
name = "submit"
class = "btn btn-default" > < i class = "fa fa-paper-plane fa-fw" > < /i> Send</button >
    <
    /div> <
    /form> <
    /div><!-- /.contact - form-- >

我的 PHP 代码是:

  <?php
      header('Content-type: application/json');

if ($_POST) {
    $to_email = "you@yourdomain.com"; //Recipient email, Replace with own email here

    //check if its an ajax request, exit if not
    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        $output = json_encode(array( //create JSON data
            'type' => 'error',
            'text' => 'Sorry Request must be Ajax POST'
        ));
        die($output); //exit script outputting json data
    }

    //Sanitize input data using PHP filter_var().
    $user_name    = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
    $user_email   = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    $phone_number = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
    $message      = filter_var($_POST["message"], FILTER_SANITIZE_STRING);

    //additional php validation
    if (strlen($user_name) < 4) { // If length is less than 4 it will output JSON error.
        $output = json_encode(array(
            'type' => 'error',
            'text' => 'Name is too short or empty!'
        ));
        die($output);
    }

    if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) { //email validation
        $output = json_encode(array(
            'type' => 'error',
            'text' => 'Please enter a valid email!'
        ));
        die($output);
    }


    if (!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)) { //check for valid numbers in phone number field
        $output = json_encode(array(
            'type' => 'error',
            'text' => 'Enter only digits in phone number'
        ));
        die($output);
    }

    if (strlen($message) < 3) { //check emtpy message
        $output = json_encode(array(
            'type' => 'error',
            'text' => 'Too short message! Please enter something.'
        ));
        die($output);
    }

    //email subject
    $subject = 'New mail via contact form';

    //email body
    $message_body = $message . "\r\n\r\n-" . $user_name . "\r\n\r\nEmail : " . $user_email . "\r\nPhone Number : " . $phone_number;

    //proceed with PHP email.
    $headers = 'From: ' . $user_name . '<' . $user_email . '>' . "\r\n" . 'Reply-To: ' . $user_name . '<' . $user_email . '>' . "\r\n" . 'X-Mailer: PHP/' . phpversion();

    $send_mail = mail($to_email, $subject, $message_body, $headers);

    if (!$send_mail) {
        //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
        $output = json_encode(array(
            'type' => 'error',
            'text' => 'Could not send mail! Please check your PHP mail configuration.'
        ));
        die($output);
    } else {
        $output = json_encode(array(
            'type' => 'success',
            'text' => 'Hi ' . $user_name . ', thank you for your email, we will get back to you shortly.'
        ));
        die($output);
    }
}


?>

【问题讨论】:

  • 如果您在联系表格中使用“必需”,则无需进行 php 验证; js 会捕捉到这一点。
  • 但是平面图的实际字体真棒继续像循环一样运行,当我托管它时它在 Cpanel 中对我不起作用(我收到发送并收到错误请检查您的邮件配置)我不会得到我的意思的实际验证(CSS部分)提前感谢@Rachel Gallen
  • 你输入的type="phone"不正确,改成type="tel"
  • 我不认为有纸飞机,如果有那不是代码

标签: php jquery html ajax forms


【解决方案1】:

您可以使用以下方法来验证表单:

$(function(){
   $('form').validate({
         'rules': {
         },
         'messages': {
         }
   })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    相关资源
    最近更新 更多