Created
July 4, 2021 20:28
-
-
Save NikitaIT/3dd2ff4073977f085419f1709b075a60 to your computer and use it in GitHub Desktop.
Vee validate handleSubmit with invalid callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PublicFormContext, SubmissionHandler } from "vee-validate"; | |
export function createSubmitHandler< | |
TValues extends Record<string, any> = Record<string, any>, | |
TContext extends Omit<PublicFormContext<TValues>, "handleSubmit"> = Omit< | |
PublicFormContext<TValues>, | |
"handleSubmit" | |
> | |
>( | |
onValid: SubmissionHandler<TValues>, | |
onInvalid: ( | |
formValues: { | |
handleSubmit: ( | |
event: Event, | |
cb: SubmissionHandler<TValues> | |
) => Promise<void>; | |
} & TContext | |
) => void | |
): ( | |
event: Event, | |
formValues: { | |
handleSubmit: ( | |
event: Event, | |
cb: SubmissionHandler<TValues> | |
) => Promise<void>; | |
} & TContext | |
) => Promise<void> { | |
return (event, formValues) => { | |
const { promise, resolve, reject } = deffer(); | |
promise.catch(() => onInvalid(formValues)); | |
const handle: SubmissionHandler<TValues> = (...args) => ( | |
resolve(), onValid(...args) | |
); | |
return formValues.handleSubmit(event, handle).then(reject); | |
}; | |
} | |
type Executor<T, TErr> = { | |
resolve: (value?: T) => void; | |
reject: (reason?: TErr) => void; | |
}; | |
function deffer<T, TError>(): { promise: Promise<T> } & Executor<T, TError> { | |
let control: any; | |
const promise = new Promise<T>( | |
(resolve, reject) => (control = { resolve, reject }) | |
); | |
return { | |
resolve: control.resolve, | |
reject: control.reject, | |
promise, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use:
Example with Focus on first invalid contorl in dom order: