Late validation on linked field
I am facing an strange issue in my Form using zod and refine a schemaa.
1. I have this schema
that is defined in an function called
takeProfitTriggerPriceShcema that retunrs zod schema
any i have two fields, Price and TriggerPrice i want everytime the price input changes to trigger validations on triggerPrice,
so i did this using linked fields7 Replies
genetic-orangeOP•5mo ago
this resulted to late validation so if for example
i changed the price input with valid value and then changed the trigger price value with invalid value (value that is larger than the price) it should trigger that the input is invalid but it doesn't i have to add one more value( one step late validation)
imagine
Price is : 60
trigger price is : 50
these are valid
then i went changed price to 49, nothing happens even this is invalid, then if i changed price to 60 it will show invalid message (which is actually the got triggered with the previous value but it didn't re-render)
eastern-cyan•5mo ago
could you wrap it as code block instead? it‘s
```tsx
done like this
```
@Othman
it helps the formatting and adds some syntax highlighting
genetic-orangeOP•5mo ago
@Luca | LeCarbonator Done, Sorry a little bit new to discord xd:)
eastern-cyan•5mo ago
it's fine! Alright, time to take a look
Alright, so to summarize:
Your field looks like this:
So, how is
currentLimitPrice defined?genetic-orangeOP•5mo ago
this is the
currentLimitPrice
;
And this is the params
t: TFunction,
price: number
price = currentLimtPriceeastern-cyan•5mo ago
the reason it's out of date by one render is probably because it sets all the validators, then triggers the rerender (which recalculates the schema to compare against for next time the field changes)
but what you actually want is for it to be up to date on the change itself. The fix for that is simple enough:
To elaborate on what exactly broke before:
1.
price changes (50 -> 49)
-> run price validation if there are any (change, onBlur etc.)
-> run fields who listen to price's changes
2. takeProfitTriggerPrice listens to price, so it will run its validators
-> The current validator is takeProfitTriggerPriceSchema(false, 50) ! we have not generated the new schema yet !
3. It passes the validation
-> finalize changes, useStore requests a rerender in React
4. Generate the new schema and assign it to the validator
This means that next time price or takeProfitTriggerPrice changes, it will use the new schema
I hope that makes sense, if not let me know @Othmangenetic-orangeOP•5mo ago
it acutally makes perfect sense, i tried now and it works, this is amazing
thank you very much