Superrefine is blocked when a Date field is not given a proper value #1212
Replies: 3 comments 3 replies
-
Yes, this is the intended behavior. Refinements are executed after the parsing of the schema. If the parsing fails, the refinement will not be executed. |
Beta Was this translation helpful? Give feedback.
-
Perhaps this will help. import { omit } from 'lodash'
const baseSchema = z.object( {
firstName: z.string(),
lastName: z.string().min( 10 ),
email: z.string().email(),
password: z.string().min( 5 ),
confirmPassword: z.string().min( 5 ),
country: z.string().refine( x => x, 'Country is required' ),
dateOfBirth: z.date().or( z.string() ).pipe( z.coerce.date() ),
} ).partial()
const schema = baseSchema.catch( ( { input, error } ) => {
const paths = error.issues.map( x => x.path ).flat()
return baseSchema.parse( omit( input, paths ) ) // omit fields with errors
} ).superRefine( ( data, ctx ) => {
if ( data.password !== data.confirmPassword ) {
ctx.addIssue( {
code: z.ZodIssueCode.custom,
message: 'Password and Confirm Password must match',
path: [ 'confirmPassword' ],
} )
}
} )
const myData = {
firstName: 'John',
lastName: '', // invalid lastName
email: '[email protected]',
password: '12345',
confirmPassword: '123456',
country: '', // missing country
dateOfBirth: '', // wrong type,
}
const result = schema.safeParse( myData )
!result.success && console.log( result.error.issues )
// [
// {
// code: 'custom',
// message: 'Password and Confirm Password must match',
// path: [ 'confirmPassword' ]
// }
// ] Let me know if you have any questions. If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
I had a problem with this because I have a dependent field being validated in the superRefine. What I did is set the the date as optional and validate it in the superRefine: Before:
The superRefine only happened when I clicked submit the button and the manual After:
Now the manual |
Beta Was this translation helpful? Give feedback.
-
When I am trying to have a superrefine run in an object that contains a date, it will not run unless the date field has a value.
Please check out the following code ( Codepen )
If you run the example above, you will see that although I have a superrefine, it doesn't get triggered unless I provide all of the values of the object, e.g. if I set dateOfBirth to new Date().
Is there a way to work around this behaviour? is this the intended behaviour? Am I doing something wrong? Please advise.
Thank you very much in advance.
Beta Was this translation helpful? Give feedback.
All reactions