11import { validate } from 'class-validator' ;
2- import { useState } from 'react' ;
2+ import { useContext , useState } from 'react' ;
3+ import { ValidatorContext } from "./context" ;
4+
5+ export { ValidatorProvider , ValidatorContextOptions , OnErrorMessageHandler } from './context' ;
36
47type Newable < T > = {
58 new ( ) : T ;
69} | Function ;
710
8- type ValidationErrorMap < T , K extends keyof T > = { [ key in K ] ?: string } ;
11+ type ValidationErrorMap < T , K extends keyof T > = { [ key in K ] ?: string [ ] } ;
912type ValidationPayload < T , K extends keyof T > = { [ key in K ] ?: T [ K ] } ;
1013type ValidationFunction < T , K extends keyof T > = ( payload : ValidationPayload < T , K > , filter ?: K [ ] ) => Promise < boolean > ;
1114type UseValidationResult < T , K extends keyof T > = [ ValidationFunction < T , K > , ValidationErrorMap < T , K > ] ;
1215
1316export const useValidation = < T , K extends keyof T > ( validationClass : Newable < T > ) : UseValidationResult < T , K > => {
1417
18+ const { onErrorMessage} = useContext ( ValidatorContext ) ;
19+
1520 const [ validationErrors , setErrors ] = useState < ValidationErrorMap < T , K > > ( { } ) ;
1621
1722 const validateCallback : ValidationFunction < T , K > = async ( payload , filter : K [ ] = [ ] ) => {
@@ -34,7 +39,7 @@ export const useValidation = <T, K extends keyof T>(validationClass: Newable<T>)
3439 const validation : ValidationErrorMap < T , K > = errors . reduce (
3540 ( acc , value ) => ( {
3641 ...acc ,
37- [ value . property as K ] : Object . keys ( value . constraints ) . map ( ( key ) => value . constraints [ key ] ) [ 0 ]
42+ [ value . property as K ] : onErrorMessage ( value )
3843 } ) ,
3944 { } as ValidationErrorMap < T , K >
4045 ) ;
0 commit comments