yii 用ckeditor验证文本字段

cnwbcb6i  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(114)

我有一个使用CKEditor的文本字段:

<div class="row">
    <?php echo $form->labelEx($model,'text'); ?>
    <?php echo $form->textArea($model, 'text', array('id'=>'editor1')); ?>
    <?php echo $form->error($model,'text'); ?>
</div>

<script type="text/javascript">
    CKEDITOR.replace( 'editor1' );
</script>

模型中的规则为

public function rules()
{
 return array(
    array('text', 'required'),
  array('text', 'validateWordLength')
);
}

public function validateWordLength($attribute,$params)
{
    $total_words= str_word_count($this->text);
    if($total_words>4000)
    {
       $this->addError('text', 'Your description length is exceeded');
    }
    if($total_words<5)
    {
       $this->addError('text', 'Your description length is too small');
    } 
}

这个很好用
1)当我将字段留空时,会出现必填文本错误。
2)当我写少于5个或多于4000个单词时,我会得到预期错误
但当我插入一些空格,然后我没有得到任何错误和形式提交。

bbmckpt7

bbmckpt71#

您可以使用正则表达式删除函数中的多个空格

public function validateWordLength($attribute,$params)
{
    $this->text = preg_replace('/\s+/', ' ',$this->text); 
    $total_words= str_word_count($this->text);
    if($total_words>4000)
    {
       $this->addError('text', 'Your description length is exceeded');
    }
    if($total_words<5)
    {
       $this->addError('text', 'Your description length is too small');
    } 
}

相关问题