2012-07-19 179 views
5

我有提交將被重定向到submit.php這種簡單的形式,如果有錯誤,它顯示submit.php錯誤消息。現在我想要的是,錯誤消息將顯示回窗體頁面。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>'; 
} 
?> 

由於此php代碼顯示在同一頁上的錯誤消息。我想在form.php page上顯示該錯誤消息。有沒有人幫我這樣做..

回答

3

This article描述您的解決方案。

你應該創建一個驗證腳本(例如validate.php),並提交形式存在的驗證。如果驗證失敗,驗證器腳本應返回一個(JSON,XML,無論您想要的)驗證錯誤數組。否則 - 返回重定向鏈接。

所以,當你點擊「提交」表單上的一個Ajax請求validator.php應該發生,而不是重定向。

你應該考慮使用框架來解決這些問題。這將節省大量的編碼時間。

1

一個簡單的解決方法是把你的註冊頁面爲您的表單操作,並與包裹PHP代碼:

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

然後你就可以複製PHP代碼,並在你的HTML頁面的開始粘貼。然後將您的表單操作設置爲您的頁面。

如果你想在處理PHP代碼隱藏表單的一部分,你可以做這樣的:

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

或者你甚至可以顯示自定義消息,用戶註冊後,中相同的形式:

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

請注意,我假設你的身體標記的其餘部分與stlye1類樣式。

這也確保只有html頁面中需要的文本,即當用戶提交表單時加載可見文本

0

正如謝爾蓋Eremin指出,這是很好的考慮這類任務的框架。

無論如何,這裏是我會怎麼做它在PHP。所有的代碼都包含一個頁面(submit.php)。所以,表單提交給自己。當用戶打開submit.php時,會顯示錶單。當他們點擊提交時,程序會檢查是否提供名稱,有效的電子郵件,喜歡的顏色和評論。如果它們中沒有一個留空並且電子郵件有效,程序將顯示「一切正常」。否則,它會將用戶重定向回窗體並指出未正確填充的字段。並且用戶以前提供的每個數據都通過重定向URL傳遞。使用$ _GET它會被檢索並顯示在表單中,所以用戶不需要從頭開始重新輸入所有內容。

請不要忘記在插入數據庫之前清理/轉義數據。

希望這會有所幫助。

<?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 
} 
?>