0

I'm using cakephp validation for a field called birthdate.

my model is

'birthdate' => array(
    'rule'       => 'date',
    'message'    => 'Enter a valid date',
    'allowEmpty' => true    
),  

my question is how come it's still save correctly even though it's invalid input. e.g:

March 27, 1988 so, if I put it like this, and the array result like this

//this will work
'birthdate' => array(
    'month' => '3#',
    'day' => '27',
    'year' => '1988'
)

//this will NOT work
'birthdate' => array(
    'month' => '#3',
    'day' => '27',
    'year' => '1988'
)

why the first one still validate it (still save correctly. e.g: the end result still march 27, 1988)? but I would like to have consistency. is there anyway to report an error?

1
  • We need some more info. Please post the form/inputs. Also, please give an example of what should and should not pass validation. Your wording of "this will work" and "will not work" aren't very helpful. Do you mean work as in it saves (which may or may not be desired), or work as in the validation is as expected? Commented Feb 8, 2014 at 5:41

1 Answer 1

1

Complex data type deconstruction

Dates are being passed as arrays, so they need to be formatted to a string first. In case the column in the database is of type date*, the value is being formatted automatically so that it fits the proper column type format.

Ultimately this is done in Model::deconstruct() (it ends up there when calling Model::set(), which normally happens before validation), where the individual values are being passed through sprintf():

$date[$index] = sprintf('%02d', $date[$index]);

https://github.com/cakephp/cakephp/blob/2.4.5/lib/Cake/Model/Model.php#L1336

Integer casting

And that's the answer to your first question, it's that formatting directive that is responsible for this behavior, it casts the individual date values to integers, where 3# evaluates to a number, while #3 fails (and ends up as 00), that's how string conversion in PHP works.

See http://php.net/manual/language.types.string.php#language.types.string.conversion

Use custom validation/formatting

So in order to be able to trigger an error on such input you'll either have to use a custom validation rule, which would require to for example pass the data using a different fieldname so that it's not being formatted in Model::set(), or use custom formatting (for example by overwriting Model::set() or Model::deconstruct()) to flatten the complex value in a way that the individual values are not being casted.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.