簡體   English   中英

表單填寫中的驗證輸入字段

[英]Validation Input Fields on Form Complete

我使用PHP創建了一個Contact表單,但是我使Submit按鈕通過Ajax腳本發送信息,因此在所有字段都完成並且用戶按下send之后,我的表單將不會關閉。

但是現在我的問題是,即使字段為空,PHP也不會發送錯誤消息,因此用戶可以看到它們。 我的問題是,如果字段為空或未按原樣編寫,如何使用echo json_encode使PHP發送錯誤消息?

信息通過Ajax腳本發送,並且驗證在PHP內部。

 $(document).ready(function(){ $("#myModal").modal('hide'); $('#contact-submit').on('click', function(){ $.ajax({ url:"forms.php", type:'post', data:$('#contact').serializeArray(), success:function(data){ $("#myElem").show(); setTimeout(function() {$ ("#myElem").hide();}, 5000); } }) }) }) 
 <?php // define variables and set to empty values $numeprodus_error = $marime_error = $nume_error = $prenume_error = $adresa_error = $oras_error = $codpostal_error = $email_error = $telefon_error = ""; $numeprodus = $marime = $nume = $prenume = $adresa = $oras = $codpostal = $email = $telefon = $message = $success = ""; //form is submitted with POST method if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["numeprodus"])) { $numeprodus_error = "Numele este Obligatoriu!"; } else { $nume = test_input($_POST["numeprodus"]); // check if nume only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$numeprodus)) { $numeprodus_error = "Doar litere sunt permise in acest camp!"; } } if (empty($_POST["marime"])) { $marime_error = "Selectati marimea!"; } else { $nume = test_input($_POST["marime"]); // check if nume only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$marime)) { $marime_error = "Doar litere sunt permise in acest camp!"; } } if (empty($_POST["nume"])) { $nume_error = "Numele este Obligatoriu!"; } else { $nume = test_input($_POST["nume"]); // check if nume only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$nume)) { $nume_error = "Doar litere sunt permise in acest camp!"; } } if (empty($_POST["adresa"])) { $adresa_error = "Adresa este obligatorie!"; } else { $adresa = test_input($_POST["adresa"]); // check if e-mail address is well-formed if (!preg_match("/[a-zA-Z0-9.]/i",$adresa)) { $adresa_error = ""; } } if (empty($_POST["oras"])) { $oras_error = "Orasul este obligatoriu!"; } else { $oras = test_input($_POST["oras"]); // check if nume only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$oras)) { $oras_error = "Doar litere sunt permise in acest camp!"; } } if (empty($_POST["codpostal"])) { $codpostal_error = "Codul postal este Obligatoriu!"; } else { $codpostal = test_input($_POST["codpostal"]); // check if e-mail address is well-formed if (!preg_match("/[0-9.]/i",$codpostal)) { $codpostal_error = "Doar cifre sunt permise in acest camp!"; } } if (empty($_POST["email"])) { $email_error = "Emailul este Obligatoriu!"; } else { $email = test_input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $email_error = "Email Invalid! Exemplu: ----@gmail.com"; } } if (empty($_POST["telefon"])) { $telefon_error = "Numarul de Telefon este Obligatoriu!"; } else { $telefon = test_input($_POST["telefon"]); // 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",$telefon)) { $telefon_error = "Numar de telefon Invalid! Minimum 10 Cifre!"; } } if (empty($_POST["message"])) { $message = ""; } else { $message = test_input($_POST["message"]); } if ($numeprodus_error == '' and $marime_error == '' and $nume_error == '' and $prenume_error == '' and $adresa_error == '' and $oras_error == '' and $codpostal_error == '' and $email_error == '' and $telefon_error == '' ){ $message_body = ''; unset($_POST['submit']); foreach ($_POST as $key => $value){ $message_body .= "$key: $value\\n"; } $to = 'andreiccl24@gmail.com'; $subject = 'Contact Form Submit'; if (mail($to, $subject, $message_body)){ $success = "Comanda a fost Trimisa, va vom contacta in maximum 24 ore pentru confirmarea ei!"; $numeprodus = $marime = $nume = $prenume = $adresa = $oras = $codpostal = $email = $telefon = $message = $success = ''; } } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } 
 <div class="container"> <div id="myModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h3 class="modal-title">Comanda prin Email</h3> <h6 style="text-align: center;">Dupa plasarea comenzi in maximum 24 ore ve-ti fi contactat Telefonic pentru confirmarea acesteia!!!</h6> </div> <div class="modal-body"> <?php include('forms.php'); ?> <div class="container"> <form id="contact" method="post"> <fieldset> <sup class="form_sup">*</sup> <select class="form-input-field" placeholder="Nume Produs" type="text" name="numeprodus" value="<?= $numeprodus ?>" tabindex="1" autofocus> <option value="" disabled selected>Produse</option> <option>A</option> <option>B</option> <option>C</option> <option>D</option> <option>E</option> <option>F</option> </select> <span class="error"><?= $numeprodus_error ?></span> </fieldset> <fieldset> <sup class="form_sup">*</sup> <select class="form-input-field" placeholder="Marimea" type="text" name="marime" value="<?= $marime_produs ?>" tabindex="2" autofocus> <option value="" disabled selected>Marimi</option> <option>S</option> <option>M</option> <option>L</option> <option>XL</option> <option>XXL</option> </select> <span class="error"><?= $marime_error ?></span> </fieldset> <fieldset> <sup class="form_sup">*</sup> <input class="form-input-field" placeholder="Nume/Prenume" type="text" name="nume" value="<?= $nume ?>" tabindex="3" autofocus> <span class="error"><?= $nume_error ?></span> </fieldset> <fieldset> <sup class="form_sup">*</sup> <input class="form-input-field" placeholder="Adresa" type="text" name="adresa" value="<?= $adresa ?>" tabindex="4" autofocus> <span class="error"><?= $adresa_error ?></span> </fieldset> <fieldset> <sup class="form_sup">*</sup> <input class="form-input-field" placeholder="Oras" type="text" name="oras" value="<?= $oras ?>" tabindex="5" autofocus> <span class="error"><?= $oras_error ?></span> </fieldset> <fieldset> <sup class="form_sup">*</sup> <input class="form-input-field" placeholder="Cod Postal" type="number" name="codpostal" value="<?= $codpostal ?>" tabindex="6" autofocus> <span class="error"><?= $codpostal_error ?></span> </fieldset> <fieldset> <sup class="form_sup">*</sup> <input class="form-input-field" placeholder="Email" type="text" name="email" value="<?= $email ?>" tabindex="7"> <span class="error"><?= $email_error ?></span> </fieldset> <fieldset> <sup class="form_sup">*</sup> <input class="form-input-field" placeholder="Telefon" type="number" name="telefon" value="<?= $telefon ?>" tabindex="8"> <span class="error"><?= $telefon_error ?></span> </fieldset> <span class="form_span">Mesaj:</span> <fieldset> <textarea cols="50" row="10" value="<?= $message ?>" name="message" tabindex="9"> </textarea> </fieldset> <fieldset> </fieldset> <div id="myElem" style="display:none">BV MA AI FACUTO</div> </form> </div> </div> <div class="dv-atentionare"><h3 class="dv-att-h3">Atentie!</h3><h6 class="dv-att-p2">Aveti la dispozitie 48 ore de la plasarea comenzi pentru ao putea anula!</h6></div> <div class="modal-footer"> <input class="btn btn-default" name="submit" type="button" id="contact-submit" data-submit="...Sending" value="Trimite"></input> <button type="button" class="btn btn-default" data-dismiss="modal">Inchide</button> </div> </div> </div> </div> </div> 

我在CSS內添加了PHP腳本,因為無處可做。

預先謝謝你們。 到現在為止,我將根據我的工作提供任何建議和批評:)

請記住,我正處於學習階段。 因此,技巧始終是我所期待的,因此我可以閱讀它。

嘗試這樣的事情:

引起錯誤時:

<?php
$errors = [];
//..
if (empty($_POST["marime"])) {
    $errors[] = "Selectati marimea!";
} else {
    $nume = test_input($_POST["marime"]);
    // check if nume only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/", $marime)) {
        $errors[] = "Doar litere sunt permise in acest camp!";
    }
}

//...
echo json_encode($errors);

嘿,我的羅馬尼亞同伴首先,您需要更改您的PHP以返回錯誤的json(如果有)或成功消息:

<?php

$numeprodus = $marime = $nume = $prenume = $adresa = $oras = $codpostal = $email = $telefon = $message = $success = "";
$errors = [];
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["numeprodus"])) {
    $errors[] = "Numele este Obligatoriu!";
  } else {
    $nume = test_input($_POST["numeprodus"]);
    // check if nume only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$numeprodus)) {
      $errors[]= "Doar litere sunt permise in acest camp!";
    }
  }


    if (empty($_POST["marime"])) {
      $errors[]= "Selectati marimea!";
    } else {
      $nume = test_input($_POST["marime"]);
      // check if nume only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$marime)) {
        $errors[]= "Doar litere sunt permise in acest camp!";
      }
    }


      if (empty($_POST["nume"])) {
        $nume_error = "Numele este Obligatoriu!";
      } else {
        $nume = test_input($_POST["nume"]);
        // check if nume only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$nume)) {
          $errors[]= "Doar litere sunt permise in acest camp!";
        }
      }


      if (empty($_POST["adresa"])) {
        $errors[]= "Adresa este obligatorie!";
      } else {
        $adresa = test_input($_POST["adresa"]);
        // check if e-mail address is well-formed
        if (!preg_match("/[a-zA-Z0-9.]/i",$adresa)) {
          $adresa_error = "";
        }
      }


        if (empty($_POST["oras"])) {
          $errors[]= "Orasul este obligatoriu!";
        } else {
          $oras = test_input($_POST["oras"]);
          // check if nume only contains letters and whitespace
          if (!preg_match("/^[a-zA-Z ]*$/",$oras)) {
            $errors[]= "Doar litere sunt permise in acest camp!";
          }
        }

      if (empty($_POST["codpostal"])) {
        $errors[]= "Codul postal este Obligatoriu!";
      } else {
        $codpostal = test_input($_POST["codpostal"]);
        // check if e-mail address is well-formed
        if (!preg_match("/[0-9.]/i",$codpostal)) {
          $errors[]= "Doar cifre sunt permise in acest camp!";
        }
      }

      if (empty($_POST["email"])) {
        $errors[]= "Emailul este Obligatoriu!";
      } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $errors[]= "Email Invalid! Exemplu: ----@gmail.com";
        }
      }

      if (empty($_POST["telefon"])) {
        $errors[]= "Numarul de Telefon este Obligatoriu!";
      } else {
        $telefon = test_input($_POST["telefon"]);
        // 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",$telefon)) {
          $errors[]= "Numar de telefon Invalid! Minimum 10 Cifre!";
        }
      }

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

      if (count($errors)) {
          $message_body = '';
          unset($_POST['submit']);
          foreach ($_POST as $key => $value){
              $message_body .=  "$key: $value\n";
          }

          $to = 'andreiccl24@gmail.com';
          $subject = 'Contact Form Submit';
          if (mail($to, $subject, $message_body)){
              $success = "Comanda a fost Trimisa, va vom contacta in maximum 24 ore pentru confirmarea ei!";
              echo json_encode(['message'=>$success]);
      } else {
             echo json_encode(['message'=>$errors,'errors'=>true]);
      }
  }

}

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

接下來在您的js中,您需要輸出ajax請求的結果,我在這里使用了一個警告框,您可以使用模式或其他方式

$('#contact-submit').on('click', function(e){
e.preventDefault();
    $.ajax({
            url:"forms.php",
          type:'post',
          data:$('#contact').serialize(),
          success:function(data){
          $("#myElem").show();
    setTimeout(function() {$ ("#myElem").hide();}, 5000);

          if(data.errors) {
            alert('Avem erori'+data.message)
          } else {
            alert('Mesaj de la ajax:'+data.message)
           }
         }
        })

 })

不要忘記阻止默認的點擊事件

暫無
暫無

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

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