CakePHP 3 - Parse Date with LocalStringFormat to correct SQL format and correct validation

后端 未结 1 1123
情书的邮戳
情书的邮戳 2020-12-20 06:22

we have declared the following lines in the initialize function of our AppController to have globally the same format for displaying dates:

    // default ti         


        
相关标签:
1条回答
  • 2020-12-20 07:12

    Parsing (in the marshalling process) and validation have nothing to do with each other, the former will happen after the latter.

    Check the date validation method API, it takes further arguments, that is, the format to use, and a custom regular expression to use instead of the predefined ones.

    date(string|DateTime $check, string|array $format 'ymd', string|null $regex null)
    

    Date validation, determines if the string passed is a valid date. keys that expect full month, day and year will validate leap years.

    Years are valid from 1800 to 2999.

    Formats:

    • dmy 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
    • mdy 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
    • ymd 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
    • ...

    [...]

    API > \Cake\Validation\Validation::date()

    So in order to properly validate your localized german data, you'll have to specify the dmy format.

    ->add('datefield', 'valid', ['rule' => ['date', 'dmy']])
    

    If you want to apply localized validation globally, in a way where the format can be changed from a single point in your app, then you could for example use a custom validation rule and a globally available custom provider, which fetches the format from your apps configuration, like

    namespace App\Validation;
    
    use Cake\Core\Configure;
    use Cake\Validation\Validation;
    
    class AppValidation
    {
        public static function date($check) {
            return Validation::date($check, Configure::read('Locale.validation.dateFormat'));
        }
    }
    
    $validator->provider('appValidation', 'App\Validation\AppValidation');
    
    $validator->add('datefield', 'valid', [
        'rule' => 'date',
        'provider' => 'appValidation'
    ])
    

    * untested example code for illustration purposes

    See also Cookbook > Validation > Custom Validation Rules

    0 讨论(0)
提交回复
热议问题