【问题标题】:Concept - Creating client side validation from PHP object概念 - 从 PHP 对象创建客户端验证
【发布时间】: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


【解决方案1】:

考虑编写验证规范,使您可以在 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 中进行类似的实现。

【讨论】:

  • 哦!这看起来确实很干净,更简洁。我想我会修改我的表格,让它看起来更像这样!完全忘记了使用 json_encode。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多