dongyi6543 2017-11-25 09:48
浏览 45

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

I have a working Java script validation code that checks my contact form and submits it, I want to add server side validation with PHP that will show sucess message once the form submitted correctly and that will send the details to my email.I am not sure how I suppose to include my php validation with my Java script one and how to show the success message. What I have so far is:

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>

My 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
";
      }

      $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;
}

I have a working Java script validation code that checks my contact form and submits it, I want to add server side validation with PHP that will show sucess message once the form submitted correctly and that will send the details to my email.I am not sure how I suppose to include my php validation with my Java script one and how to show the success message. What I have so far is:

  • 写回答

1条回答 默认 最新

  • dtv11049 2017-11-25 11:10
    关注

    You can do this best IMO, by using jquery. For that you have to adapt your PHP script a little to output json and store the error/success messages differently. Add a bit of jquery code to your existing javascript and not to forget, include the jquery library into you HTML somewhere at the bottom. For the sake of completion, i added a simple empty check on subject and message and hide the success message until the form is really sent.

    Note: You might want to remove your email from your question :)

    HTML script

    <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 script

    // 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
    ";
            }
    
            $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;
    }
    

    EDIT

    After reading your comment, it depends on what you mean by

    I copied pretty much everything you wrote

    I tested the previous code on my server and it worked well. However without your javascript validation since i removed the validation function return validateForm() so that might have confused things. To make it really work and not mixing up plain javascript with jquery, i adapted the HTML and Javascript code, so that only jQuery is used.

    Here are some troubleshooting tips in general for using ajax:

    1. The php script that processes must only output json, nothing else.
    2. Errors, warnings or notices should not be displayed (disabled) in your processing script.
    3. Make sure the file name in the ajax parameter url is correct.

    Hope this helps

    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏