在CakePHP中验证表单时显示包含变量的错误消息

时间:2010-08-29 13:19:36

标签: php cakephp validation

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

var $validate=array(

“username”=>阵列(    “usernameValid”=>阵列(      “rule”=> “__alphaNumericDashUnderscore”      “message”=> “您输入的用户名无效!”    )   )  );

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

例如,此方法__alphaNumericDashUnderscore()返回true或false,具体取决于用户输入包含禁用字符。但是,如果在这种方法中,我想返回用户键入的特定禁用字符并将其与messages一起显示?类似于"The username you entered is not valid! You have used the following forbidden characters: $chars"

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

1 个答案:

答案 0 :(得分: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
    }
}
?>