在Javascript验证之上添加带有成功消息的PHP表单验证

时间:2017-11-25 09:48:07

标签: javascript php html ajax validation

我有一个工作的Java脚本验证代码,用于检查我的联系表单并提交它,我想用PHP添加服务器端验证,一旦表单正确提交就会显示成功消息,并将详细信息发送到我的email.I我不确定如何将我的PHP验证包括在我的Java脚本中以及如何显示成功消息。到目前为止我所拥有的是:

HTML:

<form id="mc-form" method="POST">
    <div class="form-group col-xs-12 ">
        <label for="name" hidden>שם פרטי</label>
        <input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי">
        <span class='error-message' id='name-error'></span>

    </div>
    <div class="form-group col-xs-12 ">
        <label for="phone" hidden>טלפון</label>
        <input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון">
        <span class='error-message' id='phone-error'></span>
    </div>
    <div class="form-group col-xs-12 ">
        <label for="email" hidden>דואר אלקטרוני</label>
        <input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני">
        <span class='error-message' id='email-error'></span>
    </div>
    <div class="form-group col-xs-12 ">
        <label for="subject" hidden>נושא</label>
        <input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא">
    </div>
    <div class="form-group col-xs-12 ">
        <label for="message" hidden>הודעה</label>
        <textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50"></textarea>
    </div>
    <!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
    <button onclick='return validateForm()' class="btn btn-custom-outline " id="submit-button">שלח</button>
    <span class='error-message' id='submit-error'></span>
    <span class="success">Thank's for submitting the form</span>

    <br>
    <!-- <div class="success"><?= $success ?></div>-->
    <!--<span class="error"></span> -->
</form>

我的JS:

function validateName() {

    var name = document.getElementById('name').value;

    if (name.length == 0) {

        producePrompt('Name is required', 'name-error', 'red')
        return false;

    }

    if (!name.match(/^[a-zא-ת]+(\s[a-zא-ת]+)*$/i)) {

        producePrompt('Letters only please.', 'name-error', 'red');
        return false;

    }


    return true;

}

function validatePhone() {

    var phone = document.getElementById('phone').value;

    if (phone.length == 0) {
        producePrompt('Phone number is required.', 'phone-error', 'red');
        return false;
    }

    if (!phone.match(/([0-9\s\-]{7,})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/)) {
        producePrompt('Include only digits| min :8 ', 'phone-error', 'red');
        return false;
    }


    return true;

}

function validateEmail() {

    var email = document.getElementById('email').value;

    if (email.length == 0) {

        producePrompt('Email is required', 'email-error', 'red');
        return false;

    }

    if (!email.match(/^[A-Za-z\._\-[0-9]*[@][A-Za-z]*[\.][a-z]{2,4}$/)) {

        producePrompt('Email Invalid', 'email-error', 'red');
        return false;

    }


    return true;

}

/*function validateMessage() {
  var message = document.getElementById('contact-message').value;
  var required = 30;
  var left = required - message.length;

  if (left > 0) {
    producePrompt(left + ' more characters required','message-error','red');
    return false;
  }

  producePrompt('Valid', 'message-error', 'green');
  return true;

}*/

function validateForm() {
    var vn = validateName();
    var vp = validatePhone();
    var ve = validateEmail();

    if (!vn || !vp || !ve) {
        jsShow('submit-error');
        producePrompt('Please fix errors to submit.', 'submit-error', 'red');
        setTimeout(function() {
            jsHide('submit-error');
        }, 2000);
        return false;
    } else {

    }

}

function jsShow(id) {
    document.getElementById(id).style.display = 'block';
}

function jsHide(id) {
    document.getElementById(id).style.display = 'none';
}




function producePrompt(message, promptLocation, color) {

    document.getElementById(promptLocation).innerHTML = message;
    document.getElementById(promptLocation).style.color = color;


}

PHP:

// define variables and set to empty values
$name_error = $email_error = $phone_error = " ";
$name = $email = $phone = $message = $subject = $success = " ";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $name_error = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Zא-ת ]*$/",$name)) {
      $name_error = "Only letters and white space allowed"; 
    }
  }


  if (empty($_POST["email"])) {
    $email_error = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $email_error = "Invalid email format"; 
    }
  }

  if (empty($_POST["phone"])) {
    $phone_error = "Phone is required";
  } else {
    $phone = test_input($_POST["phone"]);
    // check if e-mail address is well-formed
    if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
      $phone_error = "Invalid phone number"; 
    }
  }

if (empty($_POST["subject"])) {
    $subject = "";
  } else {
    $subject = test_input($_POST["subject"]);
  }

  if (empty($_POST["message"])) {
    $message = "";
  } else {
    $message = test_input($_POST["message"]);
  }

  if ($name_error == '' and $email_error == '' and $phone_error == '' and $lastname_error == '' ){
      $message_body = '';
      unset($_POST['submit']);
      foreach ($_POST as $key => $value){
          $message_body .=  "$key: $value\n";
      }

      $to = 'ilonasemyweb@gmail.com';
      $subjectm = 'Contact Form Submit';
      if (mail($to, $subjectm, $message)){
          $success = "Message sent, thank you for contacting us!";
          $name = $lastName = $email = $phone = $message = $subject = '';
      }
  }

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

我有一个工作的Java脚本验证代码,用于检查我的联系表单并提交它,我想用PHP添加服务器端验证,一旦表单正确提交就会显示成功消息,并将详细信息发送到我的email.I我不确定如何将我的PHP验证包括在我的Java脚本中以及如何显示成功消息。到目前为止我所拥有的是:

1 个答案:

答案 0 :(得分:1)

你可以使用jquery做到最好的IMO。为此,您必须稍微调整PHP脚本以输出json并以不同方式存储错误/成功消息。在现有的javascript中添加一些jquery代码,不要忘记,在底部的某个地方将jquery库包含在HTML中。为了完成,我添加了一个简单的空主题和消息检查,并隐藏成功消息,直到表格真正发送。

注意:您可能希望从问题中删除您的电子邮件:)

HTML脚本

<style>
    .error {
        color:red;
    }
</style>
<form id="mc-form" method="POST">
    <div class="form-group col-xs-12 ">
        <label for="name" hidden>שם פרטי</label>
        <input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי">
        <span class='error-message' id='name-error'></span>

    </div>
    <div class="form-group col-xs-12 ">
        <label for="phone" hidden>טלפון</label>
        <input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון">
        <span class='error-message' id='phone-error'></span>
    </div>
    <div class="form-group col-xs-12 ">
        <label for="email" hidden>דואר אלקטרוני</label>
        <input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני">
        <span class='error-message' id='email-error'></span>
    </div>
    <div class="form-group col-xs-12 ">
        <label for="subject" hidden>נושא</label>
        <input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא">
        <span class='error-message' id='subject-error'></span>
    </div>
    <div class="form-group col-xs-12 ">
        <label for="message" hidden>הודעה</label>
        <textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50"></textarea>
        <span class='error-message' id='message-error'></span>
    </div>
    <!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
    <button class="btn btn-custom-outline " id="submit-button">שלח</button>
    <span class='error-message' id='submit-error'></span>
    <span class="success">Thank's for submitting the form</span>

</form>

<!-- load jQuery libraries -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

<强>使用Javascript / jquery的

<script type="text/javascript">

    $(document).ready(function(){

        function jsShow(id) {
            $('#'+id).show();
        }

        function jsHide(id) {
            $('#'+id).hide();
        }

        function producePrompt(message, promptLocation, color) {

            $('#'+promptLocation).text(message).css('color', color).show();

        }

        jQuery.validator.addMethod("lettersonly", function(value, element) {
            return this.optional(element) || /^[a-zא-ת]+(\s[a-zא-ת]+)*$/i.test(value);
        }, "Letters only please");
        jQuery.validator.addMethod("digitsonly", function(value, element) {
            return this.optional(element) || /([0-9\s\-]{7,})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/.test(value);
        }, "Include only digits| min :8 ");

        $('.success').hide();

        $("#mc-form").validate({
            error: function(label) {
                $(this).addClass( "error" );
            },
            rules: {
                name: {
                    required: true,
                    lettersonly: true
                },
                phone: {
                    required: true,
                    digitsonly: true
                },
                email: {
                    required: true,
                    email: true
                },
                subject: {
                    required: true,
                    minlength: 2
                },
                message: {
                    required: true,
                    minlength: 2
                }
            },
            messages: {
                name: {
                    required: "Please specify your name",
                    lettersonly: "Letters only please"
                },
                phone: {
                    required: "Phone number is required",
                    digitsonly: "Include only digits| min :8 "
                },
                email: {
                    required: "Email is required",
                    email: "Email Invalid"
                },
                subject: {
                    required: "Subject is required"
                },
                message: {
                    required: "Message is required"
                }
            },
            submitHandler: function(form) {
                sendForm();
            }
        });

        function sendForm() {

            $('[id*="-error"]').text(''); // default hide all error messages

            event.preventDefault(); // prevent form submission and therefore page reload

            $.ajax({
                type: 'POST',
                url: 'process_form.php',
                data: $("#mc-form").serialize(),
                success: function(data) {

                    if(data.hasOwnProperty('error')) {

                        Object.keys(data['error']).forEach(function(key) {
                            producePrompt(data['error'][key], key+'-error', 'red');
                        });

                    }
                    if(data.hasOwnProperty('mail_error')) {
                        alert('Could not send mail');
                    }
                    if(data.hasOwnProperty('success')) {
                        $('.success').show();
                    }
                }
            });

        }

    });
</script>

PHP脚本

// init error and success message variable to check for emptiness
$error_msg = array();
$success_msg = array();
$data = '';

// prevent warnings or errors from displaying, else you won't get proper json result
ini_set('display_errors',0);

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["name"])) {
        $error_msg['name'] = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Zא-ת ]*$/",$name)) {
            $error_msg['name'] = "Only letters and white space allowed";
        }
    }


    if (empty($_POST["email"])) {
        $error_msg['email'] = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error_msg['email'] = "Invalid email format";
        }
    }

    if (empty($_POST["phone"])) {
        $error_msg['phone'] = "Phone is required";
    } else {
        $phone = test_input($_POST["phone"]);
        // check if e-mail address is well-formed
        if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
            $error_msg['phone'] = "Invalid phone number";
        }
    }
    if (empty($_POST["subject"])) {
        $error_msg['subject'] = "Subject is required";
    }
    if (empty($_POST["message"])) {
        $error_msg['message'] = "Message is required";
    }

    if (empty($_POST["subject"])) {
        $subject = "";
    } else {
        $subject = test_input($_POST["subject"]);
    }

    if (empty($_POST["message"])) {
        $message = "";
    } else {
        $message = test_input($_POST["message"]);
    }

    if (empty($error_msg)){ // note that $lastname_error does not exists
        $message_body = '';
        unset($_POST['submit']);
        foreach ($_POST as $key => $value){
            $message_body .=  "$key: $value\n";
        }

        $to = 'xxxxxxxxx@gmail.com';
        $subjectm = 'Contact Form Submit';
        if (mail($to, $subjectm, $message)){
            $success_msg = "Message sent, thank you for contacting us!";
            $name = $email = $phone = $message = $subject = '';
        } else {
            $mail_error_msg = 'Could not send email';
        }


    }

    // set output data accordingly
    if(!empty($success_msg)) {
        $data = array('success'=>$error_msg);
    } else if(!empty($error_msg)) {
        $data = array('error'=>$error_msg);
    } else if(!empty($mail_error_msg)) {
        $data = array('mail_error'=>$mail_error_msg);
    }

    // output json that you can parse with jquery
    header('Content-Type: application/json');
    echo json_encode($data);
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

修改

阅读完评论后,这取决于您的意思

  

我复制了你写的所有内容

我在我的服务器上测试了以前的代码并且运行良好。但是没有你的javascript验证,因为我删除了验证函数return validateForm(),这可能会让事情变得混乱。为了使它真正起作用而不是将简单的javascript与jquery混合,我调整了HTML和Javascript代码,以便只使用jQuery。

以下是一般使用ajax的疑难解答提示:

  1. 处理的php脚本必须只输出json,没有别的。
  2. 不应在处理脚本中显示(禁用)错误,警告或通知。
  3. 确保ajax参数url中的文件名正确无误。
  4. 希望这有帮助