acfo/form-validation

1.0.1 2017-11-12 15:15 UTC

This package is not auto-updated.

Last update: 2024-09-29 04:14:33 UTC


README

#表单验证

严格类型HTML 5兼容的表单验证类。

###安装

composer require acfo/form-validation

###用法

使用提供的FormImpl特质在您的表单验证类中实现Form接口。将表单字段作为属性添加(例如登录表单)

class LoginForm implements Form
{
    use FormImpl;
    
    private $email;
    private $password;
    
    public function __construct()
    {
        $this->email = new Email(Requirement::Required);
        $this->password = new Password(Requirement::Required);
    }
    
    public function getEmail()
    {
        return $this->email;
    }
    
    public function getPassword()
    {
        return $this->password();
    }
}

表单验证类可用于向视图提供客户端验证参数。

<form method="post" action="#">
    <input 
        name="email" 
        type="email" 
        minlength="<?= $loginForm->getEmail()->getMinLength() ?>" 
        maxlength="<?= $loginForm->getEmail()->getMaxLength() ?>"
        pattern="<?= $loginForm->getEmail()->getPattern() ?>"
        <?= $loginForm->getEmail()->getRequired() ?>
        >
    <input 
        name="password" 
        type="password" 
        minlength="<?= $loginForm->getPassword()->getMinLength() ?>" 
        maxlength="<?= $loginForm->getPassword()->getMaxLength() ?>"
        pattern="<?= $loginForm->getPassword()->getPattern() ?>"
        <?= $loginForm->getPassword->getRequired() ?>
        >
    <input type="submit">    
</form>

要执行GET或POST表单输入的服务器端验证,请调用validate。

$loginForm = new LoginForm();

if (!$loginForm->validate($_POST)) {
    die('please do not try and feed me invalid data');
}

在大多数情况下,客户端验证会触发错误消息并阻止无效数据发送到服务器。服务器端验证的唯一目的是保护服务器免受恶意输入的侵害。

对于那些仅依赖于服务器端验证进行表单数据验证的情况,显示错误的责任也可能在服务器端。

验证错误存储在表单字段对象上。表单字段方法getError将返回空字符串、'error missing'、'error invalid'或由附加业务逻辑特别设置时返回'error requirements'。错误字符串可用于在视图中显示错误消息,例如。

CSS

.feedback.missing, 
.feedback.invalid {
    display: none;
}

.error.missing .feedback.missing,
.error.invalid .feedback.invalid {
	color: red;
	display: block;
}

HTML

<form method="post" action="#">
    <div class="<?= $loginForm->getEmail()->getError() ?>">
        <input 
            name="email" 
            type="email" 
            >
        <p class="feedback missing">Please enter your email.</p>
        <p class="feedback invalid">What you entered does not seem to be an email. Please try again.</p>
    </div>
    <div class="<?= $loginForm->getPassword()->getError() ?>">
        <input 
            name="password" 
            type="password" 
            >
        <p class="feedback missing">Please enter your password</p>
        <p class="feedback invalid">Your password has to be between 6 and 60 characters long</p>
    </div>
    <input type="submit">    
</form>

###预定义表单字段

通用表单字段

  • 复选框
  • ConstListItem
  • 日期
  • ListItem
  • 数字
  • 文本

账户表单字段

  • 电子邮件
  • 密码

地址表单字段

  • 城市
  • 姓名
  • 街道
  • 邮政编码

搜索表单字段

  • 搜索字符串

享受吧!