php 表单验证代码(验证失败显示提示信息)

前端之家收集整理的这篇文章主要介绍了php 表单验证代码(验证失败显示提示信息)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:

<?PHP
/**
 * 表单验证
 *
 * @param 
 * @arrange (512.笔记) jb51.cc
 **/
function validatePost( $regs,$ferrors )
{
 $errors = array();
 foreach( $regs as $k => $v )
 {
  if( ! preg_match( $v,$_POST[$k] ) )
  {
   $errors[$k] = $ferrors[$k];
  }
 }
 return $errors;
}
 
 
// has the post been submitted?
if( count( $_POST ) )
{
 // yes it has been submitted so lets validate
 $regs['last_name']  = "/^[[:alpha:]\ -]+$/";  // require a alpha
 $regs['first_name'] = "/^[[:alpha:]\ -]+$/";  // require a alpha
 $regs['email']      = "/^..*\@..*$/";         // VERY simple email check
                                             // Use google to find better
 
 
 // Ok here are the error message to display when it is bad
 $ferrors['last_name']  = "Last name required";
 $ferrors['first_name'] = "First name required";
 $ferrors['email']      = "Email name required";
 
 $errors = validatePost( $regs,$ferrors );
 
 // Do we have errors?
 if( count( $errors ) == 0 )
 {
  //  WE HAVE NO ERRORS DO SOMETHING
  //  PUT IT INTO THE DATABASE,EMAIL,BOUNCE THE USER
  //  TO A THANK YOU PAGE,ETC...
 }
}
?>
经测试代码如下:

<!-- OK WE ARE IN HTML -->
<!-- LETS MAKE THE FORM AND NOW YOU SEE HOW SIMPLE THIS IS I HOPE -->
 
<form method="POST">
 
<p>
<label>Last Name</label>
<input type="text" name="last_name" value="<?= $_POST['last_name'] ?>" />
<span style="color: #FF0000;"><?= $errors['last_name'] ?></span>
</p>
 
 
<p>
<label>First Name</label>
<input type="text" name="first_name" value="<?= $_POST['first_name'] ?>" />
<span style="color: #FF0000;"><?= $errors['first_name'] ?></span>
</p>
 
 
<p>
<label>Email</label>
<input type="text" name="email" value="<?= $_POST['email'] ?>" />
<span style="color: #FF0000;"><?= $errors['email'] ?></span>
</p>
 
 
<p>
<input type="submit" name="subby" value="GO" />
</p>
 
 
</form>

猜你在找的PHP相关文章