PHP注册表单验证

eja*_*jaz 5 php forms validation

我有这个简单的表单提交它将被重定向到submit.php,如果有错误,它会显示错误消息submit.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>';
}
?>
Run Code Online (Sandbox Code Playgroud)

因为这个PHP代码在同一页面上显示错误消息.我想在上面显示错误消息form.php page.有没有人帮我这样做..

Ser*_*min 3

本文介绍了您的解决方案。

您应该创建一个验证器脚本(例如 validate.php)并在那里提交表单进行验证。如果验证失败,验证器脚本应返回验证错误数组(JSON、XML,无论您想要什么)。否则 - 返回重定向链接。

因此,当您单击表单上的“提交”时,应该会发生对 validator.php 的 AJAX 请求,而不是重定向。

您应该考虑使用框架来解决此类问题。这将节省大量编码时间。