First solution
Create a NumberFormat class inside of InvoiceData and use the same formatting props, to retrieves its removeFormatting function
InvoiceData.js
const getProperties = ({ invoice, register, errors }) => ({
customInput: TextField,
inputRef: register,
variant: "outlined",
name: "amountToPay",
label: "InvoiceData.amountToPay",
helperText: ((errors || {}).amountToPay || {}).message,
error: (errors || {}).amountToPay,
thousandSeparator: " ",
suffix: " PLN",
defaultValue: (invoice || {}).amountToPay,
decimalScale: 2,
fixedDecimalScale: true
});
export const removeFormatting = (value, props = {}) => {
const properties = getProperties(props);
let res = Number.parseFloat(
new NumberFormat(properties).removeFormatting(value)
);
if (properties.decimalScale) {
return res * Math.pow(10, -properties.decimalScale);
}
return res;
};
You can then use that function to check if your submitted form is valid:
Form.js
const onSubmit = async (data) => {
if (removeFormatting(data.amountToPay) === responseData.amountGross) {
// action when valid
console.log("valid");
} else {
// action when invalid
}
};
see your modified code using this link :
https://codesandbox.io/s/heuristic-paper-4ycuh
Second solution
Use a state to remember the amountToPay such as follow:
const [amountToPay, setAmountToPay] = useState(responseData.amountToPay)
Add a callback function to your InvoiceData component and use onValueChange from NumberFormat to call that function, e.g. :
const InvoiceData = ({...props, handleChanged} => {
return (
<NumberFormat
// whatever props you need
onValueChange={(value) => handleChanged(value.floatValue)}
/>
);
}
You can then pass on the setAmountToPay that we defined previously, and pass it to InvoiceData in that manner:
<InvoiceData
// whatever props you need
handleChanged={setAmountToPay}
/>
You can then validate your submit as follow
const onSubmit = async () => {
if (amountToPay === responseData.amountGross) {
// action when valid
console.log("valid");
} else {
// action when invalid
}
};