kayode / form-validator
表单验证库
dev-master
2020-11-01 23:00 UTC
This package is auto-updated.
Last update: 2024-09-29 06:02:48 UTC
README
请注意,此项目是一个开源项目。如果出现问题且我无法快速响应,请尽量贡献并修复问题。
文档
安装
运行以下命令
$ composer require kayode/form-validator
方法与属性
此库具有以下方法和属性
use FormValidator\Form; $validator = new form($_POST); //validate methods: this is the method were you will be setting your validation rules $validator->validate([]); //passed methods: this methods will be use to check if each input passed the validation rules $validator->passed(); //errors property: this property will be use to output all errors $validator->errors[]; //errors property is the only available property
设置表单验证规则
使用 $validator->validate([])
方法设置验证规则示例
<?php use FormValidator\Form; $validator = new form($_POST); //check if the request methid is post if($_SERVER['REQUEST_METHOD'] === 'POST') { $validator->validate([ 'first_name' => 'required|string|min|3', 'last_name' => 'required|string|min|3', 'github_link' => 'required|url', ]); } ?>
表单将看起来像
<form action='' method='POST'>
<input type='text' name='first_name'><br>
<input type='text' name='last_name'>
<input type='text' name='github_link'>
<button type='submit' name="submit">submit</button>
</form>
输出错误
使用 $validator->errors
属性输出表单错误
<form action='' method='POST'> <?php if($validator->errors['first_name']) echo '<p>'.$validator->errors['first_name'].'</p>'; ?> <input type='text' name='first_name'><br> <?php if($validator->errors['last_name']) echo '<p>'.$validator->errors['last_name'].'</p>'; ?> <input type='text' name='last_name'> <?php if($validator->errors['github_link']) echo '<p>'.$validator->errors['github_link'].'</p>'; ?> <input type='text' name='github_link'><br> <button type='submit' name="submit">submit</button> </form>
遍历错误
<form action='' method='POST'> <?php foreach($validator->errors as $error) { echo '<p>'.$error.'</p>'; } ?> <input type='text' name='first_name'><br> <input type='text' name='last_name'> <input type='text' name='github_link'><br> <button type='submit' name="submit">submit</button> </form>
如何使用最小和最大验证规则
要使用 min
或 max
验证规则,下一个值必须是 min 或 max 的值
$validator->validate([ 'minimum' => 'min|3', 'maximum' => 'max|6', ]);
通过
要检查每个表单是否通过了验证规则,请使用 $validator->passed()
方法
if($validator->passed()){ echo 'submited sucessfully'; }
所有可用的验证规则
这些是所有可用的验证规则的列表
required
=> 验证空字段string
=> 验证字符串email
=> 验证电子邮件url
=> 验证 URLnumeric
=> 验证数字int
=> 验证整数float
=> 验证浮点数min
=> 验证输入字段的最低值max
=> 验证输入字段的最高值
这是一个开源项目,您可以为添加更多验证规则做出贡献