概念 - 从 PHP 对象创建客户端验证


Concept - Creating client side validation from PHP object

我正在制作自己的MVC框架,我正在考虑一种"自动"客户端验证控制器的方法。

在其他功能中,我的表单、元素和验证器是像这样协同工作的对象(在表单对象内部):

$this->addElement('text', 'myInput');
$this->elements['myInput']->addValidators(array
    'length' => array('min' => 5, 'max' => 10),
    'number' => array('decimals' => 0)
));

在上面的例子中,我创建了一个名为"myInput"的文本输入,根据我添加的验证器,其值:

  • 必须为>= 超过 5 个字符
  • 必须为 <= 超过 10 个字符
  • 必须是数字
  • 不得有小数(仅限整数)

当我收到表单提交并调用验证函数时,一切都在服务器端运行良好。但是,困扰我的是必须手动在客户端重做验证。我不喜欢复制相同的功能,所以我想出了一种方法来从已经存在的 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>

我正在寻找关于如何与另一种技术一起工作的大拇指或建议。如果你有什么想法,我想听听!

考虑以这样一种方式编写验证规范,以便您可以在 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中进行类似的实现。