CakePHP日期验证与JQuery日期选择器

3
我正在尝试在CakePHP中使用JQuery的日期选择器。我似乎无法弄清楚如何做到这一点,并同时使用CakePHP内置的日期验证以及允许任何日期格式。我找到的所有答案都涉及复杂的解决方案。我感觉必须有一种简单的方法来实现这一点,因为JQuery日期选择器是一个很常见的东西。
目前,我正在尝试将日期转换为CakePHP日期数组格式。
array( 'day' => '21', 'month' => '3', 'year' => '1993' )

这会在输入无效数据时导致问题。它会在任何空日期字段中放置两个空格,而strtotime将空格视为“现在”。因此,如果输入无效数据并且用户重新发送数据,则会将任何空日期字段(不需要填写)保存为今天的日期。
有什么想法吗?
1个回答

1
尝试类似以下代码:
在模型中:
/*...*/
    $validate = array( 
        'your_date' => array(
            'date' => array(
                //Add 'ymd' to the rule.
                'rule' => array('date', 'ymd'),
                'message' => 'Please select a valid birth date.',
            ),
        ),
    );
/*...*/

在控制器中:
//Put into a function so you can reuse the same code.
function convertDates( &$data ){
    if (!empty($data['date_of_birth']) && strtotime($data['date_of_birth']) ){
        $data['date_of_birth'] = date('Y-m-d', strtotime($data['date_of_birth']));
    }
}

调用上述函数的函数:

public function add() {
    /*...*/
    //Convert the dates to YYYY-MM-DD format before attempting to save.
    $this->convertDates( $this->request->data['ModelName'] );
    /*...*/
}

在视图中:
/*...*/
//Make input form a text field, and give it a class of datepicker (or whatever).
echo $this->Form->input('date_of_birth', array(
    'class'=>'datepicker', 'type'=>'text','label'=>'Date of Birth'
    )
);
/*...*/

然后在底部添加您的初始化脚本:

<script>
//Initialize your datepicker at the bottom.
    $(document).ready(function() {
        $( "input.datepicker" ).datepicker({
            yearRange: "-100:+50",
            changeMonth: true,
            changeYear: true,
            constrainInput: false,
            showOn: 'both',
            buttonImage: "/img/calendar.png",
            buttonImageOnly: true
        });
    });
</script>

1
非常好,谢谢!我错过了文档(如果有的话)说明如何修改日期规则的行为。 - Devin H.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接