Validation for “at least one phone number is required” in CakePHP

给你一囗甜甜゛ 提交于 2019-12-08 04:53:15

问题


This is the model file vechile_enquiry.php

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

This is the view file vechile.ctp

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

At least one phone number is required:

<?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));
?>

Validation is working in the name field but I'm not getting how to implement validation in mobile_phone, work_phone, home_phone for the condition that at least one phone number is required.


回答1:


This should do it for you:

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


来源:https://stackoverflow.com/questions/9719033/validation-for-at-least-one-phone-number-is-required-in-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!