yii2 ActiveForm数字文本字段

yii2 ActiveForm数字文本字段,yii2,yii2-advanced-app,active-form,Yii2,Yii2 Advanced App,Active Form,我使用yii2创建了一个ActiveForm,如下所示: <?=$form->field($item, 'finalPrice', [ 'options' => [ 'tag' => 'div', 'class'

我使用yii2创建了一个ActiveForm,如下所示:

                            <?=$form->field($item, 'finalPrice', [
                                'options' => [
                                    'tag' => 'div',
                                    'class' => '',
                                ],
                                'template' => '<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label>{input}{error}</span>'
                            ])->textInput([
                                 // ** i want numeric value **
                            ])->label(false)?>

您可以使用
->textInput(['type'=>'number']
例如:

<?=$form->field($item, 'finalPrice', [
                                'options' => [
                                    'tag' => 'div',
                                    'class' => '',
                                ],
                                'template' => '<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label>{input}{error}</span>'
                            ])->textInput([
                                 'type' => 'number'
                            ])->label(false)?>

试试这个。它对我有用

<?= $form->field($model, 'amount')->textInput(['type' => 'number']) ?>

字段,如电话号码/会员号码等,有时我们只允许用户在文本字段中输入数字。在这种情况下,应用模式匹配规则对我来说非常有用

只需在模型类中设置一个规则,您就完成了

public function rules()
{
    return [
...

 [['contactno'], 'string', 'max' => 25],
 [['contactno'], 'match' ,'pattern'=>'/^[0-9]+$/u', 'message'=> 'Contact No can Contain only numeric characters.'], 

...
          ];
}


还可以指定
min
max
step
值。
@WaiHaLee:此答案中没有链接。这只是另一个答案的复制粘贴。
public function rules()
{
    return [
...

 [['contactno'], 'string', 'max' => 25],
 [['contactno'], 'match' ,'pattern'=>'/^[0-9]+$/u', 'message'=> 'Contact No can Contain only numeric characters.'], 

...
          ];
}
<?= $form->field($model, 'code')->textInput(['type'=>'number']) ?>