diff --git a/src/products/components/ProductPricing/ProductPricing.tsx b/src/products/components/ProductPricing/ProductPricing.tsx index 0c53611db..790f12784 100644 --- a/src/products/components/ProductPricing/ProductPricing.tsx +++ b/src/products/components/ProductPricing/ProductPricing.tsx @@ -5,6 +5,7 @@ import CardTitle from "@saleor/components/CardTitle"; import PriceField from "@saleor/components/PriceField"; import { ProductErrorFragment } from "@saleor/fragments/types/ProductErrorFragment"; import { getFormErrors, getProductErrorMessage } from "@saleor/utils/errors"; +import createNonNegativeValueChangeHandler from "@saleor/utils/handlers/nonNegativeValueChangeHandler"; import React from "react"; import { useIntl } from "react-intl"; @@ -37,11 +38,7 @@ const ProductPricing: React.FC = props => { const formErrors = getFormErrors(["basePrice"], errors); - const handlePriceChange = event => { - if (/^\d*(\.\d+)?$/.test(event.target.value)) { - onChange(event); - } - }; + const handlePriceChange = createNonNegativeValueChangeHandler(onChange); return ( diff --git a/src/products/components/ProductVariantPrice/ProductVariantPrice.tsx b/src/products/components/ProductVariantPrice/ProductVariantPrice.tsx index d8092219c..0712f5cfe 100644 --- a/src/products/components/ProductVariantPrice/ProductVariantPrice.tsx +++ b/src/products/components/ProductVariantPrice/ProductVariantPrice.tsx @@ -5,6 +5,7 @@ import CardTitle from "@saleor/components/CardTitle"; import PriceField from "@saleor/components/PriceField"; import { ProductErrorFragment } from "@saleor/fragments/types/ProductErrorFragment"; import { getFormErrors, getProductErrorMessage } from "@saleor/utils/errors"; +import createNonNegativeValueChangeHandler from "@saleor/utils/handlers/nonNegativeValueChangeHandler"; import React from "react"; import { useIntl } from "react-intl"; @@ -36,11 +37,7 @@ const ProductVariantPrice: React.FC = props => { const formErrors = getFormErrors(["price", "cost_price"], errors); - const handlePriceChange = event => { - if (/^\d*(\.\d+)?$/.test(event.target.value)) { - onChange(event); - } - }; + const handlePriceChange = createNonNegativeValueChangeHandler(onChange); return ( diff --git a/src/utils/handlers/nonNegativeValueChangeHandler.ts b/src/utils/handlers/nonNegativeValueChangeHandler.ts new file mode 100644 index 000000000..a8d4e53dd --- /dev/null +++ b/src/utils/handlers/nonNegativeValueChangeHandler.ts @@ -0,0 +1,11 @@ +import { FormChange } from "@saleor/hooks/useForm"; + +function createNonNegativeValueChangeHandler(change: FormChange) { + return (event: React.ChangeEvent) => { + if (/^\d*(\.\d+)?$/.test(event.target.value)) { + change(event); + } + }; +} + +export default createNonNegativeValueChangeHandler;