在CakePHP中验证“至少需要一个电话号码”

时间:2012-03-15 11:46:48

标签: php validation cakephp cakephp-1.3

这是模型文件vechile_enquiry.php

<?php
    class VechileEnquiry  extends AppModel{
        var $name ='VechileEnquiry';
        var $validate = array('name' => array
                                            ('rule' => 'notEmpty',
                                            'message' => 'Please type name')
                            );
    }
?>

这是视图文件vechile.ctp

<?php
    echo $this->Form->input('name', array('label'=>false));
?>

至少需要一个电话号码:

<?php
    echo $this->Form->input('mobile_phone', array('label'=>false));
    echo $this->Form->input('work_phone', array('label'=>false));
    echo $this->Form->input('home_phone', array('label'=>false));
?>

验证在名称字段中有效,但我没有得到如何在mobile_phone中实现验证, work_phonehome_phone,条件是至少需要一个电话号码。

1 个答案:

答案 0 :(得分:1)

这应该适合你:

    var $validate = array(
    'name' => array(
        'rule' => 'notEmpty',
        'message' => 'Please type name'
    ),
    'mobile_phone' => array(
        'check_phone' => array(
            'rule' => array('hasPhone'),
            'required' => false,
            'allowEmpty' => true,
            'message' => 'At least one phone number is required.'
        )
    ),
    'work_phone' => array(
        'check_phone' => array(
            'rule' => array('hasPhone'),
            'required' => false,
            'allowEmpty' => true,
            'message' => 'At least one phone number is required.'
        )
    ),
    'home_phone' => array(
        'check_phone' => array(
            'rule' => array('hasPhone'),
            'required' => false,
            'allowEmpty' => true,
            'message' => 'At least one phone number is required.'
        )
    )
); 


function hasPhone($field){
    if(!empty($this->data[$this->name]['mobile_phone']) || !empty($this->data[$this->name]['work_phone']) || !empty($this->data[$this->name]['home_phone'])){
        return true;
    } else {
        return false;
    }
}