【问题标题】:Display error messages containing variables when validating forms in CakePHP在 CakePHP 中验证表单时显示包含变量的错误消息
【发布时间】:2010-08-29 13:19:35
【问题描述】:

我的模型中有 $validate 变量,其中包含:

var $validate=array(

"用户名" => 数组( “用户名有效” => 数组( "规则" => "__alphaNumericDashUnderscore", "message" => "您输入的用户名无效!" ) ) );

问题是:如何从__alphaNumericDashUnderscore()验证方法中返回错误信息,并将其扔到规则数组中的message键中?

例如,__alphaNumericDashUnderscore() 这个方法返回真或假,这取决于用户输入是否包含禁止字符。但是,如果在这种方法中,我想返回用户输入了哪些特定的禁止字符并将它们与messages 一起显示呢?类似"The username you entered is not valid! You have used the following forbidden characters: $chars"

您知道如何实现这一目标吗?提前谢谢你。

【问题讨论】:

    标签: php cakephp validation


    【解决方案1】:

    默认情况下,CakePHP 验证方法只返回 True 或 False。但它仍然是 PHP。你可以做任何事情。这是我的技巧:

    <?php
    class User extends Model {
        var $name = 'User';
        var $invalidChars = "";
        var $validate=array("username" => array( "usernameValid" => array( 
            "rule" => "__alphaNumericDashUnderscore", 
            "message" => "The username you entered is not valid! You have used the following forbidden characters: $this->invalidChars" 
        )));
    
        function alphaNumericDashUnderscore($check) {
            // Process the value
            // Assign invalid char, $this->invalidChars = $chars
            // Return true or false
        }
    }
    ?>
    

    【讨论】:

    • 您好,非常感谢!我没有遇到过这个解决方案。这是我一直在寻找的,再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 2019-06-11
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    相关资源
    最近更新 更多