我正在制作自己的 MVC 框架,并且正在考虑一种方法来实现“自动”客户端验证 Controller 。
在其他功能中,我的表单、元素和验证器是像这样一起工作的对象(在表单对象内部):
$this->addElement('text', 'myInput');
$this->elements['myInput']->addValidators(array
'length' => array('min' => 5, 'max' => 10),
'number' => array('decimals' => 0)
));
在上面的示例中,我创建了一个名为“myInput”的文本输入,根据我添加的验证器,其值是:
- 必须 >= 5 个字符
- 必须 <= 超过 10 个字符
- 必须是数字
- 不得包含小数(仅限 int)
当我收到表单提交并调用验证函数时,一切都在服务器端运行良好。然而,令我困扰的是必须在客户端手动重新进行验证。我不喜欢重复相同的功能,因此我想出了一种从已有的 PHP 表单对象创建客户端验证的方法。
它归结为拥有与 PHP 验证器具有相同功能的 JS 验证器函数,并在元素上调用 getClientValidatiors() 函数来创建适当的 <script>
在附加 JS 事件的正文中。
注意:请忽略 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;
}
例如, View 中的内容如下:
<?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>
我正在寻找关于如何将其与另一种技术结合使用的赞许或建议。如果您有任何想法,我想听听!
最佳答案
考虑以可以在 JavaScript 和 PHP 中自动验证的方式编写验证规范。
$input_schema = array(
"foo" => array(
"type" => "number",
"decimals" => 0,
"length" => array(
"min" => 5,
"max' => 10
)
)
);
然后在 JS 中你可以这样做:
var input_schema = <?php echo json_encode($input_schema);?>;
function validate_input(form_values) {
for (var key in input_schema) {
validate_property(input_schema[key], form_values[key]);
}
}
function validate_property(schema_property, value) {
if (schema_property.type === "number") {
validate_number(schema_property, value); // etc
}
}
您也可以在 PHP 中进行类似的实现。
关于javascript - 概念 - 从 PHP 对象创建客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793652/