【发布时间】:2016-01-14 15:42:20
【问题描述】:
我正在制作自己的 MVC 框架,并且正在考虑一种方法来实现“自动”客户端验证控制器。
在其他功能中,我的表单、元素和验证器是一起工作的对象,有点像这样(在表单对象内部):
$this->addElement('text', 'myInput');
$this->elements['myInput']->addValidators(array
'length' => array('min' => 5, 'max' => 10),
'number' => array('decimals' => 0)
));
在上面的示例中,根据我添加的验证器,我创建了一个名为“myInput”的文本输入:
- 必须>= 5 个字符
- 必须
- 必须是数字
- 不能有小数(仅限整数)
当我收到表单提交并调用验证函数时,在服务器端一切正常。然而,困扰我的是不得不在客户端手动重做验证。我不喜欢复制相同的功能,所以我想出了一种方法来从已经存在的 PHP 表单对象创建客户端验证。
它归结为拥有与 PHP 验证器具有相同功能的 JS 验证器函数,并在元素上调用 getClientValidatiors() 函数以在附加 JS 事件的主体中创建适当的<script>。
注意:请忽略 JS 错误,我把它写成一个概念,还没有测试任何东西。
JS 验证器函数的工作方式如下:
function lengthValidator(options, value, id){
//Validate according to the options. Return true if valid or false otherwise as well as calling printError function with the message and the id
}
function numberValidator(options, value, id){
//Validate according to the options. Return true if valid or false otherwise as well as calling printError function with the message and the id
}
function printError(error, id){
//Might add more functionality later
document.getElementById(id).innerHTML = error;
}
例如,这就是它在视图中的样子:
<?php echo $this->form->elements['myInput]; //The HTML ?>
<?php echo $this->form->elements['myInput]->getClientValidators(); //The JS ?>
在表单提交之前,结果如下所示:
<input type="text" name="myInput" id="myInput"/>
<span class="error" id="myInput-error"></span>
<script>
document.getElementById('myInput').addEventListener('blur', function(e){
var value = e.value;
var id = e.id + '-error';
if(lengthValidator({min:5, max:10}, value, id) != true){
return;
}
if(numberValidator({decimals:0}, value, id) != true){
return;
}
});
</script>
我正在寻找有关如何将其与另一种技术一起使用的竖起大拇指或建议。如果您有任何想法,我想听听!
【问题讨论】:
-
这种问题在code review上可能会更好
-
谢谢,我马上换。除了 stackoverflow 什么都不习惯,我的错!
标签: javascript php forms object model-view-controller