0

I have this Html where a user can introdue a price:

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

I have this jquery so if the user introduce for example "2" in the input will appear "2,00":

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

Now Im in doubt how to validate the price and how to store the price in db. In the database i created the column "price" as a decimal. It should be inserted in the database "2" or "2,00"?

And in validate method how to validate if the price has the valid format?

$this->validate($request, [
       ...
        'registration_type_price' => 'required|double',
 ]);

2 Answers2

1

Its your choice how you want to display the price in the view. But in DB you want to store the currency as integer format and store the cents.

For example if you have $15.50 you would store 1550 (this applies to any currency and not just USD). Read more here: Why not use Double or Float to represent currency?

Also, if you handle multiple currency, create a varchar field to store currency such as GBP, USD etc. For info on currency codes : https://en.wikipedia.org/wiki/ISO_4217

m1alesis
  • 670
  • 6
  • 16
0

Your POST value seems to be a float so,

Use regex

$regex = "/^(?=.+)(?:[1-9]\d*|0)?(?:\.\d+)?$/";
$this->validate($request, [
   ...
    'registration_type_price' => 'required|regex:'.$regex,
 ]);

Let me know if not work

afsal c
  • 612
  • 4
  • 12