在 ZF3 中:假设您有一个用于验证用户输入数据的表单类
namespace Application\Form;
use Zend\Form\Form;
use Zend\Form\Element\Text;
class UserForm extends Form
{
public function __construct()
{
parent::__construct();
$this->addElements();
$this->addInputFilter();
}
/**
* Add elements to the form
*/
private function addElements()
{
$usernameElement = new Text('username');
$usernameElement->setAttribute('id', 'username');
$passwordElement = new Text('password');
$passwordElement->setAttribute('id', 'password');
$this->add($usernameElement)
->add($passwordElement);
}
/**
* Add filters and validators
*/
private function addInputFilter()
{
$inputFilter = $this->getInputFilter();
$inputFilter->add([
'name' => 'username',
'required' => true,
'filters' => [
[
'name' => 'StringTrim',
],
[
'name' => 'StringToLower',
],
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'min' => 1,
'max' => 255,
],
],
[
'name' => 'Regex',
'options' => [
'pattern' => '/[a-z0-9_]+/',
],
],
],
]);
// add filters and validators for other fields here..
}
/**
* Make a set of fields required / not required
*/
public function setFieldsRequirement(array $fieldNames, bool $isRequired = false)
{
foreach ($fieldNames as $fieldName) {
$this->getInputFilter()
->get($fieldName)
->setRequired($isRequired);
}
}
}
在控制器中使用:
$form = new UserForm();
// get form data from POST params
$formData = $this->params()->fromPost();
$form->setData($formData);
// make username and password not required
$form->setFieldsRequirement(['username', 'password'], false);
if ($form->isValid()) {
// from data processing...
}