繁体   English   中英

yii验证输入的电话号码数组

[英]yii validate an input array of phone numbers

我正在使用Yii 1.1.16中的多联系表格。 用户可以在哪里添加多个电话号码。

问题是,我如何使用Yii的rules()来验证这一点?

<div class="form-group">
                <?php 
                echo $form->labelEx($model,'contacts', array('class'=>'col-md-3 control-label')); 
                ?>
                  <div class="col-md-9">
                    <div class="multiple-contact multiple-form-group input-group padding-bottom-10px" data-max="5">
                            <div class="input-group-btn input-group-select">
                                <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                    <span class="concept">Phone</span> <i class="fa fa-caret-down"></i>
                                </button>
                                <ul class="dropdown-menu" role="menu">
                                    <li><a href="#phone">Phone</a></li>
                                    <li><a href="#fax">Fax</a></li>
                                    <li><a href="#mobile">Mobile</a></li>
                                </ul>
                                <?php echo $form->textField($model,'contacts',array('type'=>'text', 'class'=>'input-group-select-val', 'name'=>'contacts[type][]','value'=>'phone')); ?>
                            </div>

                            <?php echo $form->textField($model,'contacts',array('size'=>60,'maxlength'=>255, 'name'=>'contacts[value][]','class'=>'form-control')); ?>
                            <?php echo $form->error($model,'contacts'); ?>
                            <span class="input-group-btn">
                                <button type="button" class="btn btn-success btn-add"><i class="fa fa-plus"></i></button>
                            </span>
                   </div>
                 </div>
            </div>

我尝试使用它,但不起作用

public function rules()
{
        return array(
    array('contacts[value][]', 'required'),
    array('contacts[value][]', 'integerOnly'=>true),
    array('contacts[value][]','type','type'=>'array','allowEmpty'=>false)
    );
}

这是一个关于jQuery方面如何工作的示例小提琴 我希望它能够使用'enableAjaxValidation'=>true,进行验证。 此外,当添加更多字段时,它会复制输入的id 没有ajax帖子是onblur/onfocus

使用自定义验证。

在规则中声明自定义验证器,并在验证器方法中定义所需的验证。

public function rules()
{
    return array(
      array('contacts', validateContacts),
    );
}

public function validateContacts($attribute,$params)
{
   if (length($this->contacts) == 0) {
      $this->addError($attribute, 'You must add at least one contact!');
   }
   foreach($this->contacts as $contact) {
      // ...
   }

}

在控制器中,将contacts数组分配给Model字段并调用模型的验证方法。 如果有任何错误,它将通过该行显示

<?php echo $form->error($model,'contacts'); ?>

在视图中。

控制器包含调用验证的代码。

$contactModel = new Contact;
// assign the array of contacts to the model
$contactModel->contacts = $POST['myForm]['contacts']
$contactsModel->validate();

$this->render('myform', contactModel);

如果您希望通过Ajax进行验证,则需要在创建表单时指定:

$form=$this->beginWidget('CActiveForm', array(
   'id'=>'top-websites-cr-form',
   'enableAjaxValidation'=>true,
   'clientOptions' => array(
      'validateOnSubmit'=>true,
      'validateOnChange'=>true),
));

在这种情况下,您的控制器可以检查ajax表单。

if(isset($_POST['ajax']) && $_POST['ajax']==='branch-form')
{
   echo CActiveForm::validate($model);
   Yii::app()->end();
}

参考文献: http//www.yiiframework.com/wiki/168/create-your-own-validation-rule/

您应该使用它自己的验证使其成为一个单独的模型。 然后在您的控制器中,您必须分别验证主要模型和相关模型。

以下是此类设置的良好指南: http//www.yiiframework.com/wiki/384/creating-and-updating-model-and-its-related-models-in-one-form-inc-image/

对于关于phonenumbers的最佳验证,我应该使用libphonenumber php库,并且有一个关于yii框架的扩展,例如http://www.yiiframework.com/extension/libphonenumber/

基本用法:

Yii::setPathOfAlias('libphonenumber',Yii::getPathOfAlias('application.vendors.libphonenumber'));
$phonenumber=new libphonenumber\LibPhone($your_phone_number);
$phonenumber->validate();

有关libphonenumber php库的用法和功能的更多详细信息,请访问: https//github.com/davideme/libphonenumber-for-PHP

让我们考虑你有一个名为ContactNo的模型,它看起来像

    class ContactNo extends CFormModel
    {
        public $contact;

        public function rules()
        {
            return array(
// your rules  
                array('contact', 'required'),
                array('contact','length','min'=>2)
            );
        }

        /**
         * Declares attribute labels.
         */
        public function attributeLabels()
        {
            return array(
                'contact'=>'Contact No',
            );
        }
    }

控制器为SiteController ,操作名称为actionIndex

然后你的控制器应该看起来像这样

public function actionIndex()
        {
// set how many contact fields you want here
                $contactCount = 3;

                $models = array();

                if(isset($_POST['ContactNo']))
                {
                    $successModels = 0;
                    foreach($_POST['ContactNo'] as $key=>$value)
                    {
                        $model = new ContactNo;
                        $model->attributes = $value;

                        if($model->validate()) // this validates your model
                            $successModels++; // it tells how many contact No.s have been validated

                        $models[$key]=$model;
                    }

// if all the contact nos are validated, then perform your task here
                    if($successModels === $contactCount)
                    {
                        // save your models
                        echo 'models saved';
                        Yii::app()->end();
                    }
                }
                else
                {
                    for($index = 0;$index < $contactCount; $index++)
                    $models[] =  new ContactNo;
                }

                $params = array();

                $params['contactCount']=$contactCount;
                $params['models']= $models;

                $this->render('index',$params);
        }

现在让我们来看看。 显然,视图是index.php ,它将是类似的东西

// Include all the initial part required for activeforms

    <?php echo $form->errorSummary($models); ?>

            <?php foreach ($models as $index=>$model): ?>
        <div class="row">
            <?php echo $form->labelEx($model,"[{$index}]contact"); ?>
            <?php echo $form->textField($model,"[{$index}]contact",array('size'=>60,'maxlength'=>128)); ?>
            <?php echo $form->error($model,"[{$index}]contact"); ?>
        </div>
            <?php endforeach; ?>

// Include the submit button

希望这有助于您或者至少为您提供一个实现目标的想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM