php - Display error messages containing variables when validating forms in CakePHP

952

I have the $validate variable in my model which contains:

var $validate=array(

"username" => array( "usernameValid" => array( "rule" => "__alphaNumericDashUnderscore", "message" => "The username you entered is not valid!" ) ) );

The question is: how do I return an error message from the__alphaNumericDashUnderscore() validation method and throw it in themessage key in the rules array?

For example, this method,__alphaNumericDashUnderscore(), returns true or false, depending on the user input contains forbidden characters. But what if in this method, I would like to return which specific forbidden characters the user has typed and display them together with themessages? Something like"The username you entered is not valid! You have used the following forbidden characters: $chars".

Do you have any idea of how to achieve this? Thank you in advance.

68

Answer

Solution:

By default, CakePHP validation method only return True or False. But it is still PHP. You can do anything. Here is my hack :

<?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
    }
}
?>

People are also looking for solutions to the problem: regex - word boundary on non latin characters in php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.