我有以下字段
<?= $form->field($model, 'phone')
->textInput(['type' => 'number', 'maxlength' => 13])
->label('Phone')
?>
为什么'maxlength'
不起作用?以及如何使它工作?
之前谢谢你
答案 0 :(得分:0)
由于您在输入字段中使用type=>number
,因此无效,您必须将其更改为type=>text
。
<?= $form->field($model, 'phone')
->textInput(['type' => 'text', 'maxlength' => 13])
->label('Phone')
?>
查看您的输入似乎是在执行此操作,因为您不希望用户输入除Phone
字段的数字之外的任何其他内容,Yii2
为您提供了一种非常好的方法来完成这个yii\widgets\MaskedInput
,你可以使用mask
选项格式化你的输入,告诉它允许多少位数,以及在哪个序列中看到演示HERE
<?= $form->field($model, 'phone')->widget(\yii\widgets\MaskedInput::className(), [
'mask' => '999-999-9999',
]) ?>
除了上述解决方案之外,您还可以选择使用自定义验证选项在模型中验证此内容。
您的模型中的电话规则应如下
[['phone'],'PhoneLimit']
public function PhoneLimit($attribute)
{
if (!preg_match('/^[0-9]{13}$/', $this->$attribute)) {
$this->addError($attribute, 'Please provide digits only no more than 13.');
}
}
答案 1 :(得分:0)
尝试输入数字->'type'=>'number','min'=> 1,'max'=> 999