How to create floating point validation with two decimals in Yii2?

不羁岁月 提交于 2019-12-13 04:39:11

问题


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); }



来源:https://stackoverflow.com/questions/33123647/how-to-create-floating-point-validation-with-two-decimals-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!