如何在输入中显示带小数个案的价格,但在store()上没有整数valdidation错误?

时间:2018-04-17 18:30:53

标签: php jquery laravel

我有下面的jQuery并且它工作,当插入价格输入中的值时,例如“3”它添加“3,00”但是然后在控制器中有一个验证错误,说价格是整数。你知道如何纠正这个问题吗?也就是说,将价格保持为整数,但没有验证错误。

PostController中:

$prod = Product::create([
     'price' => $request->price,
]);

输入:

<div class="form-group col-md-6">
    <label for="price">Price></label>
    <input type="number" min="1" step="any" required class="form-control" value="{{ old('price', '0.00€') }}"  name="price" id="price"/>
</div>

jQuery的:

 document.getElementById("price").onblur =function (){
    this.value = parseFloat(this.value.replace(/,|\€/g, ""))
        .toFixed(2)
        .toString()
        .replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

1 个答案:

答案 0 :(得分:0)

如果您希望将用户原始输入数据发送到后端,同时在前端(在同一输入框中)显示其数据,则可以使用您设置的隐藏表单字段用户输入了一个值。

<div class="form-group col-md-6">
    <label for="price">Price></label>
    <input type="hidden" name="price" />
    <input type="number" min="1" step="any" required class="form-control" value="{{ old('price', '0.00€') }}"  name="show-price" id="price"/>
</div>

然后,当您的用户离开输入字段时,您可以格式化输入,同时将隐藏输入设置为原始值预格式化:

 document.getElementById("show-price").onblur =function (){
    var $price = document.getElementById("price");
    $price.value = this.value;
    this.value = parseFloat(this.value.replace(/,|\€/g, ""))
        .toFixed(2)
        .toString()
        .replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

我不能确定输入是什么,就像#show-price一样,所以你可能需要将它格式化一点以将其修剪成一个裸整数,但是想法是在你执行视觉之前格式化您将隐藏的表单字段值设置为原始数据。