2012-07-19 34 views
5

Tôi có biểu mẫu đơn giản này khi gửi nó sẽ được chuyển hướng đến submit.php, nếu có lỗi, nó hiển thị thông báo lỗi trên submit.php. Bây giờ những gì tôi muốn rằng các thông báo lỗi sẽ được hiển thị trở lại trang biểu mẫu.Xác thực mẫu đăng ký PHP

<html> 
<head> 
<? require_once('lib.php'); ?> 
</head> 
<body> 
<form name="my-form" id="my-form" method="post" action="submit.php"> 
     Your name: 
     <input name="name" value="" size="30" maxlength="255" /> 
     Your email: 
     <input name="email" value="" size="30" maxlength="255" /> 
     Your favourite color: 
      <select name="fav_color"> 
       <option value="">-select please-</option> 
       <option value="Black">Black</option> 
       <option value="White">White</option> 
       <option value="Blue">Blue</option> 
       <option value="Red">Red</option> 
       <option value="Yellow">Yellow</option> 
      </select> 
     Your comment: 
     <textarea name="comment" rows="6" cols="35"></textarea> 
    <input type="submit" value="Submit" />   
</form> 
</body> 
</html> 
<?php 

require_once('lib.php'); 

function getErrors($postData,$rules){ 

    $errors = array(); 

    // validate each existing input 
    foreach($postData as $name => $value){ 

    //if rule not found, skip loop iteration 
    if(!isset($rules[$name])){ 
     continue;  
    } 

    //convert special characters to HTML entities 
    $fieldName = htmlspecialchars($name); 

    $rule = $rules[$name]; 

    //check required values 
    if(isset($rule['required']) && $rule['required'] && !$value){ 
     $errors[] = 'Field '.$fieldName.' is required.'; 
    } 

    //check field's minimum length 
    if(isset($rule['minlength']) && strlen($value) < $rule['minlength']){ 
     $errors[] = $fieldName.' should be at least '.$rule['minlength'].' characters length.';  
    } 

    //verify email address  
    if(isset($rule['email']) && $rule['email'] && !filter_var($value,FILTER_VALIDATE_EMAIL)){ 
     $errors[] = $fieldName.' must be valid email address.'; 
    } 

    $rules[$name]['found'] = true; 

    } 


    //check for missing inputs 
    foreach($rules as $name => $values){ 
    if(!isset($values['found']) && isset($values['required']) && $values['required']){ 
     $errors[] = 'Field '.htmlspecialchars($name).' is required.'; 
    } 

    } 

    return $errors; 
} 

$errors = getErrors($_POST,$validation_rules); 

if(!count($errors)){ 
    echo 'Your form has no errors.'; 
} 
else{ 
    echo '<strong>Errors found in form:</strong><ul><li>'; 
    echo join('</li><li>',$errors); 
    echo '</li></ul><p>Correct your errors and try again.</p>'; 
} 
?> 

Khi mã php này hiển thị thông báo lỗi trên cùng một trang. Tôi muốn hiển thị thông báo lỗi đó trên form.php page. Có ai giúp tôi làm như vậy không ..

Trả lời

3

This article mô tả giải pháp của bạn.

Bạn nên tạo tập lệnh xác thực (ví dụ: validate.php) và gửi biểu mẫu ở đó để xác thực. Nếu việc xác thực không thành công, tập lệnh validator sẽ trả về một mảng các lỗi xác thực (JSON, XML, bất kỳ thứ gì bạn muốn). Khác - trả về liên kết chuyển hướng.

Vì vậy, khi bạn nhấp vào "gửi" trên biểu mẫu của bạn, yêu cầu AJAX đến validator.php sẽ xảy ra, không phải chuyển hướng.

Bạn nên cân nhắc sử dụng khung cho các vấn đề như vậy. Nó sẽ tiết kiệm rất nhiều thời gian mã hóa.

1

Một giải pháp đơn giản là đặt trang đăng ký của bạn như hình thức hành động của bạn, và quấn mã php với:

if(isset($_POST['submit'])){ 
    //php code here 
} 

Sau đó, bạn có thể sao chép mã php và dán nó vào đầu trang html của bạn. Sau đó, đặt hành động biểu mẫu của bạn vào trang của bạn.

Nếu bạn muốn ẩn một phần của hình thức khi mã PHP được xử lý, bạn có thể làm điều đó như thế này ::

echo '<style>.style1 {display: none }</style>"; 

hoặc thậm chí bạn có thể hiển thị một thông báo tùy chỉnh cho người dùng sau khi đăng ký trong các hình thức tương tự:

echo '<div class="highlight"><p class="textcenter"><h5>You have successfully registered for blah blah blah.</h5></p><p>Thank you!</p><style>.style1 {display: none }</style>"; 

Lưu ý rằng tôi giả định rằng phần còn lại của thẻ cơ thể của bạn là phong cách với lớp stlye1.

Điều này cũng đảm bảo chỉ văn bản cần thiết trong trang html tức là văn bản hiển thị được tải khi người dùng gửi biểu mẫu.

0

Như Sergey Eremin đã chỉ ra, bạn nên xem xét một khuôn khổ cho loại nhiệm vụ này.

Dù sao, đây là cách tôi sẽ làm điều đó trong PHP. Tất cả các mã được chứa một trang (submit.php). Vì vậy, biểu mẫu gửi đến chính nó. Khi người dùng mở tệp submit.php, biểu mẫu được hiển thị. Khi họ nhấp vào gửi, chương trình sẽ kiểm tra xem tên, email hợp lệ, màu yêu thích và nhận xét được cung cấp. Nếu không ai trong số họ bị bỏ trống và email hợp lệ, chương trình sẽ hiển thị "Mọi thứ đều ổn". Nếu không, nó sẽ chuyển hướng người dùng trở lại biểu mẫu và chỉ các trường chưa được điền đầy đủ. Và mọi dữ liệu mà người dùng đã cung cấp trước đó đều được chuyển qua URL chuyển hướng. Sử dụng $ _GET nó được lấy ra và hiển thị trong biểu mẫu để người dùng không cần phải gõ lại mọi thứ từ đầu.

Vui lòng không quên xóa/thoát dữ liệu trước khi chèn vào cơ sở dữ liệu.

Hy vọng điều này sẽ hữu ích.

<?php 
    //if the form has been submitted 
    if (isset($_POST['submit'])){ 

     //extract data submitted through the form and assign date to variables 
     $name = $_POST['name']; 
     $email = $_POST['email']; 
     $favoriteColor = $_POST['fav_color']; 
     $comment = $_POST['comment']; 

     //pattern against which to check email validity 
     $good_email = "[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}"; 

     //if provided data is valid (email especially) and no form field has been left empty display "everything is okay" 
     if(strlen($name) > 0 && strlen($email) > 0 && preg_match("/$good_email/", $email, $regs) && strlen($favoriteColor) > 0 && strlen($comment) > 0){ 
      echo "Everything is okay"; 
     } 
     //otherwise redirect the user back to the form and indicate errors that they need to correct 
     else{ 

      //build an error message string where the user is shown where the issue is 
      $error_message = "There are errors with your form."; //starting point for the error message 

      //if message has been left empty let the user know that the name is required 
      if(strlen($name) == 0){ 
       $error_message .= "<br/>Name is required"; 
      } 
      //if the email is left empty let the user know that an email is required 
      if(strlen($email) == 0){ 
       $error_message .= "<br/>Email is required"; 
      } 
      //if the email does not match the pattern ($good_email) let the user know that the email they have supplied is invalid 
      if(!(preg_match("/$good_email/", $email, $regs))){ 
       $error_message .= "<br/>Email is not valid"; 
      } 
      //if the a favorite color has not been selected let the user know that they need to select a favorite color 
      if(strlen($favoriteColor) == 0){ 
       $error_message .= "<br/>Favorite color can not be left empty"; 
      } 
      //if the comment is left empty let the user know that comment is required 
      if(strlen($comment) == 0){ 
       $error_message .= "<br/>Comment is required"; 
      } 
      //if any field is left empty or the email is invalid redirect the user back to the form along with the data they submitted 
      header("Location: submit.php?&submittedName=$name&error=$error_message&submittedEmail=$email&submittedColor=$favoriteColor&submittedComment=$comment"); 
     } 
    } 
    //if no submission display the form 
    else{ 
?> 
<html> 
<head> 

</head> 
<body> 

<?php 
    //display the error message 
    //error message is passed through the url 
    if (isset($_GET['error'])) 
    { 
     echo "<p style='color:red'>".$_GET['error']."</a>"; 
    } 
?> 
<form name="my-form" id="my-form" method="post" action="submit.php"> 
     Your name: 
     <input name="name" value="<?php if($_GET['error']) { echo $_GET['submittedName'];} //if there's been an error with form submission display the name the user prevously submitted ?>" size="30" maxlength="255" /> 
     Your email: 
     <input name="email" value="<?php if($_GET['error']) { echo $_GET['submittedEmail'];} //if there's been an error with form submission display the email the user prevously submitted ?>" size="30" maxlength="255" /> 
     Your favorite color: 
      <select name="fav_color"> 
       <option value="">-select please-</option> 
       <option value="Black">Black</option> 
       <option value="White">White</option> 
       <option value="Blue">Blue</option> 
       <option value="Red">Red</option> 
       <option value="Yellow">Yellow</option> 
      </select> 
     Your comment: 
     <textarea name="comment" rows="6" cols="35"><?php if($_GET['error']) { echo $_GET['submittedComment'];} //if there's been an error with form submission display the comment the user prevously submitted ?></textarea> 
    <input type="submit" value="Submit" name="submit"/>   
</form> 
</body> 
</html> 
<?php 
} 
?> 
Các vấn đề liên quan