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

内容摘要
这篇文章主要为大家详细介绍了php 表单验证代码(验证失败显示提示信息),具有一定的参考价值,可以用来参考一下。

对此感兴趣的朋友,看看idc笔记做的技术笔记。经测试代码如下:

<
文章正文

这篇文章主要为大家详细介绍了php 表单验证代码(验证失败显示提示信息),具有一定的参考价值,可以用来参考一下。

对此感兴趣的朋友,看看idc笔记做的技术笔记。经测试代码如下:

<?php
/**
 * 表单验证
 *
 * @param 
 * @arrange (www.idcnote.com)
 **/
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 表单验证代码(验证失败显示提示信息)的内容就先介绍到这里,更多相关文章的可以留意

代码注释

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!