简体   繁体   English

在yii框架上进行一次验证来收集多个输入

[英]Collect multi inputs with to one validation on yii framework

I'm using Yii framework and I have form with 3 inputs for phone number. 我使用的是Yii框架,并且我有带3个电话号码输入的表格。 I split it for this format (XXX-XXX-XXXX) every split by minus is input. 我将其分割为这种格式(XXX-XXX-XXXX),每次输入减一会被输入。
I want to validate it after user change/pass all 3 fields and give one error message if it is not valid. 我想在用户更改/通过所有3个字段后对其进行验证,如果无效,则给出一条错误消息。 I want to save it with the same order and split it back to the same format. 我想以相同的顺序保存它,并将其拆分回相同的格式。

This is example of my code. 这是我的代码示例。

    <?php echo $form->labelEx($model,'phone'); ?>

<?php echo $form->textField($model,'phone[0]'); ?>
<?php echo $form->textField($model,'phone[1]'); ?>
<?php echo $form->textField($model,'phone[2]'); ?>

How can I do that? 我怎样才能做到这一点?

You can validate inputs at the controller and add error if needed: 您可以在控制器上验证输入并根据需要添加错误:

// ...
$validator = new CRegularExpressionValidator;
$validator->pattern = '/^[0-9]{3}\-[0-9]{3}\-[0-9]{3}/';
if ( !$validator->validate( $model->phone[0] ) ) // Do this for all of your phone fields!
{
    // add error if not added yet: $model->addError( ... );
}
if ( $model->validate( null, false ) ) // notice the 2nd argument!
{
    // ...
}

Or you can define your own validator at the model class with pretty the same code (this is the better option I believe). 或者,您可以使用几乎相同的代码在模型类中定义自己的验证器(我相信这是更好的选择)。

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

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