我创建了一个支持多维数组验证的Validation类,我想使用它,但我不知道Phalcon如何检索验证实例。
我该怎么做?
这是我的MultiDimensionalValidator类:
/**
* Validates inputs with multidimensional names such as "names[fr]name'.
*
* @package Intlist\Validator
*/
class MultidimensionalValidator extends Validation
{
/**
* @param \Phalcon\Validation $validation
* @param string $attribute
*
* @return Validation\Message\Group|void
*/
public function validate($validation = null, $attribute = null)
{
$this->_data = $validation->_data;
$this->_messages = $validation->getMessages();
foreach ($this->_validators as $validator) {
$validator->validate($this, $attribute);
}
return $this->_messages;
}
/**
* Support for multidimensional array.
*
* @inheritdoc
*/
public function getValue($attribute)
{
$parts = $this->extractKeyParts($attribute);
$value = $this->_data;
while ($name = array_shift($parts)) {
if (!array_key_exists($name, $value)) {
return null;
}
$value = $value[$name];
}
return $value;
}
/**
* Extract the parts from a flattened multidimensional key.
*
* @param string $flattened
*
* @return array
*/
private function extractKeyParts($flattened)
{
$pos = strpos($flattened, '[');
if (!$pos) {
return [ $flattened ];
}
$first = substr($flattened, 0, $pos);
$remainder = substr($flattened, $pos);
preg_match_all('#\[([^\]]+)\]#', $remainder, $matches);
return array_merge([ $first], $matches[1]);
}
}
这是用法:
foreach ($this->domain->getLanguages() as $language) {
$name = new Text("names[$language][name]");
$name->setLabel($t('common.label.category_name') . " ($language)");
$name->addValidator(new MultiDimensionalValidator([
new PresenceOf(['message' => $t('validation.category_name.required')]),
new StringLength([
'max' => 255,
'messageMaximum' => 'validation.category_name.messageMaximum'
])
]));
}
MultiDimensionalValidator类在这里用作验证器,但我真的想将它用作表单的验证实例。
答案 0 :(得分:0)
如果要将自定义验证器与表单结合使用,则需要将元素添加到表单中,如下所示:
$form->add($name);
根据文档(http://docs.phalconphp.com/en/latest/reference/forms.html#validation),您可以使用isValid方法验证您的数据:
if (!$form->isValid($_POST)) {
foreach ($form->getMessages() as $message) {
echo $message, '<br>';
}
}
但请注意,Phalcon验证组件(http://docs.phalconphp.com/en/latest/reference/validation.html)与表单无关。换句话说,它不必是表单的一部分。它可以是模型的一部分,或者它可以是一个独立的类,如下例所示:
$validation = new Phalcon\Validation();
foreach ($this->domain->getLanguages() as $language) {
$validation->addValidator(new MultiDimensionalValidator(...));
}
$messages = $validation->validate($_POST);
if (count($messages)) {
foreach ($messages as $message) {
echo $message, '<br>';
}
}