2012-07-19 146 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 
} 
?>