How to create floating point validation with two d

2019-09-11 15:59发布

问题:

I have tried creating a validation for a field which stores unit price of a product, I come across validation showing how to check for integer, but I can't found one for floating point number something with a format like 2032.95 in YII2. Thanks in advance.

*

After Abilay instructions I tried

  • [['quantity','round_off'],'number','numberPattern'=>'[-+]?[0-9]*.[0-9]+|[0-9]+'],

but it shows error in console.

回答1:

I think, redefining of numberPattern of NumberValidator class will help in your case.


If you use AJAX Validator on your form:

  1. In Model:
    [['quantity','round_off'], 'number', 'numberPattern' => '/^\d+(.\d{1,2})?$/'],
  2. In View:
    Ensure that you enabled AJAX Validation when created form
    $form = ActiveForm::begin([ 'id' => 'my-form', 'enableAjaxValidation' => true, ]);
    and change field to default input
    $form->field($model, 'quantity')

  3. In Controller:
    Include files:
    use yii\web\Response; use yii\widgets\ActiveForm;
    Past this code at the beginning of action, after $model is loaded or created
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); }