yii2active-form

Yii2 ActiveForm TextField Number Max


I have fields like below

<?= $form->field($model, 'phone')
->textInput(['type' => 'number', 'maxlength' => 13])
->label('Phone') 
?>

why the 'maxlength' is not work? and how to make it work?

thank you before


Solution

  • It will not work because you are using type=>number for your input field, you have to change it to type=>text.

    <?= $form->field($model, 'phone')
    ->textInput(['type' => 'text', 'maxlength' => 13])
    ->label('Phone') 
    ?>
    

    Looking at your input it seems like you are doing it because you do not want the user to enter any other thing than numbers for the Phone field, Yii2 provides you a very nice way to accomplish this i.e yii\widgets\MaskedInput, you can format your input using the mask option to tell it how many digits to allow and in which sequence see the demos HERE

    <?= $form->field($model, 'phone')->widget(\yii\widgets\MaskedInput::className(), [
        'mask' => '999-999-9999',
    ]) ?>
    

    apart from the solutions above, you can also have the option of validating this inside your model by using the custom validation option.

    Your rule for phone inside your model should look like

    [['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.');
        }
    }