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.
I think, redefining of numberPattern of NumberValidator class will help in your case.
If you use AJAX Validator on your form:
- In Model:
[['quantity','round_off'], 'number',
'numberPattern' => '/^\d+(.\d{1,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')
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);
}