duanke1286 2015-06-03 09:45
浏览 25

Yii自定义验证 - 类验证包含1个抽象方法

I have some validation methods that I need to use for multiple models. For example validation of phone numbers can be shared across multiple models.

I understand from http://www.yiiframework.com/wiki/56/ I can create an extension that can be used by multiple models, for example:

array('phone', 'ext.Validate.Validate'),

I have modified this line a few times and can confirm it is hitting the right file.

With the following in Validate.php

class Validate

I get the error Call to undefined method Validate::applyTo(), therefore I have changed it to

class Validate extends CValidator

As suggested by the link above, however I now get the error:

Class Validate contains 1 abstract method

Here is the file as it stands:

<?php

class Validate extends CValidator
{
    public function phone($phone)
    {
        if(!ctype_digit($phone))
        {
            $this->addError($phone, Yii::t('flash','flash.not_authorised',array('{attribute}'=>$phone)).' '.ucfirst(str_replace('_', ' ', $phone)).' field');
        }
        else
        {
            return true;
        }
    }
}

Can someone point me in the right direction as to how I can have a shared validation between multiple methods using the above.

  • 写回答

1条回答 默认 最新

  • dousuitang5239 2015-06-03 10:33
    关注

    Ok I managed to solve this.

    I found the following after a few hours of searching http://www.yiiframework.com/wiki/56/

    The main issue is tat you need the following method in your class, when extending CValidator:

    protected function validateAttribute($object,$attribute)
    {
    
    }
    

    Here is the model code (yii/protected/extension/Validate/Validate.php)

    array('phone', 'ext.Validate.Validate'),
    

    Here is the class code:

    <?php
    
    class Validate extends CValidator
    {
        protected function validateAttribute($object,$attribute)
        {
            self::{$attribute."Validation"}($object,$attribute);   
        }
    
    
        protected function phoneValidation($object,$attribute)
        {
            if(!empty($object->$attribute))
            {
                if(!ctype_digit($object->$attribute))
                {
                     $this->addError($object,$attribute,Yii::t('app','validation.telephon_failed',array('{attribute}'=>ucwords($attribute))));
                }
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)