在使用PHPMailer发送邮件之前,应该验证表单

时间:2018-06-08 08:10:57

标签: php jquery validation phpmailer

我正在使用phpmailer处理表单。这里phpmailer工作正常,但在发送邮件之前,我想使用js.validation验证我的表单不起作用我应该如何在使用js发送邮件之前验证表单。我必须为此写一个条件,任何人都可以帮助我,我尝试了很多方面,但没有实现它。 以下是我的代码 HTML

    <form method="post" action="script.php" id="test" novalidate>
                        <div class="detail">
                            <label>name:</label>
                            <input type="text" name="user_name"  data-validation="name" />
                        </div><!--detail-->
                        <div class="detail">
                            <label>Email:</label>
                            <input type="email" name="user_email" data-validation="email"/>
                        </div><!--detail-->
                        <div class="detail">
                            <label>phone</label>
                            <input type="number" name="user_phone" data-validation="phone" />
                        </div><!--detail-->
                        <div class="detail">
                            <label></label>
                            <input type="text" name="user_enquiry" data-validation="message" />
                        </div><!--detail-->
                        <div class="detail message">
                            <label>Message:</label>
                            <textarea  name="user_message" cols="30" rows="15" data-validation="message"></textarea>
                        </div><!--detail-->
                        <p><input type="submit" name="send" id="send" value="Send" onclick="formSubmit();" /></p>
                        <div class="success_msg">
                            <p>Form submitted Successfully</p>
                        </div> 
                    </form>

JS:

function formSubmit(){
    var Validator = function(formObject) {
    this.form = $(formObject);
    var Elements = {
        name: {
            reg: /^[a-zA-Z]{2,20}$/,
            require : true,
            error: "Not a valid name.",
        },

        email: {
            reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
            error: "Not a valid e-mail address.",
        },
        phone: {
            reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
            error: "Not a valid number.",
        },

        message: {
            reg: /^(?!\s*$).+/,
            error: "Message field cannot be empty.",
        },
        gender: {
          error: "gender is required",
        },
        selectOption: {
          error: "this field is required",
          required: true
      }
    };

    var handleError = function(element, message) {
        element.addClass('input-error');
        var $err_msg = element.parent('div');
        $err_msg.find('.error').remove();

        var error = $('<div class="error"></div>').text(message);
        error.appendTo($err_msg);
        console.log(element);


      element.on('keypress change', function() {
            $(error).fadeOut(1000, function() {
            console.log(element);
            element.removeClass('input-error');
            });
        });

    };

    /* Select Option */

    this.validate = function() {
      var errorCount = 0;

      this.form.find("select").each(function(index, field){
         var type = $(field).data("validation");
            var validation = Elements[type];
          if($(field).val() == "") {
            errorCount++;                       
            handleError($(field), validation.error);
          }
      });

        this.form.find("input, textarea").each(function(index, field){
            var type = $(field).data("validation");
            var validation = Elements[type];
            if(validation !== undefined) {            
             var re = new RegExp(validation.reg);                
             if (validation){                   
                 if (!re.test($(field).val())){ 
                    errorCount++;                       
                    handleError($(field), validation.error);                    
                }
             }
         }
        })

    /* Radio button */  

    var radioList = $('input:radio');
    var radioNameList = new Array();
    var radioUniqueNameList = new Array();
    var notCompleted = 0;
    for(var i=0; i< radioList.length; i++){
      radioNameList.push(radioList[i].name);
    }
    radioUniqueNameList = jQuery.unique( radioNameList );
    console.log(radioUniqueNameList);
    for(var i=0; i< radioUniqueNameList.length; i++){
        var field = $('#' + radioUniqueNameList[i]);
        var type = field.data("validation");
           var validation = Elements[type];
        if($('input[name='+type+']:checked', '#test').val() == undefined) {
            errorCount++;   
            handleError($(field), validation.error);
        }
    }

    return errorCount == 0;
    };
};

/* Submit form*/

 $(function(){

    $('form#test').on('submit', function (e) {
      var NoErrors =  new Validator(this).validate();
      if(NoErrors == true) {
          $.ajax({
              url: this.action,
              type: this.method,
              data: $(this).serialize(),
              success: function() {
                  // AJAX request finished, handle the results and error msg
                 $('.success_msg').fadeIn().delay(3000).fadeOut();         
                 //$('input[type=text], input[type=number], input[type=email], textarea').val('').removeClass('error');
                 $('input[type!="submit"], textarea').val('').removeClass('error');
                 //this.reset();
              }
          });

      }
         return false;
     })

 })
}//formSubmit

PHP:

   <?php

include "classes/class.phpmailer.php";

$mail = new PHPMailer;                                // Passing `true` enables exceptions
$mail->IsSMTP();                                      // Set mailer to use SMTP
$mail->SMTPDebug = 1;                                 // Enable verbose debug output
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted

$mail->Host = 'smtp.gmail.com';                       // Specify main and backup SMTP servers
$mail->Port = 587;                                    // TCP port to connect to
$mail->IsHTML(true);                                  // Set email format to HTML
$mail->Username = '***********';       // SMTP username
$mail->Password = '**********';                    // SMTP password
$mail->SetFrom('**************');


$msg = 'Name : ' . $_POST["user_name"] . '<br> Email : ' . $_POST["user_email"] . '<br> Phone : ' . $_POST["user_phone"]  . '<br> Enquiry : ' . $_POST["user_enquiry"]  . '<br> Message : ' . $_POST["user_message"];
$mail->Subject = "subject here";


$mail->Body = $msg;
$mail->AddAddress($_POST["user_email"]);

if(!$mail->Send()){
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}else{
    echo 'Message has been sent with using SMTP.';
}

 ?>

0 个答案:

没有答案