Created
December 8, 2022 09:28
-
-
Save aliakakis/6f7c675e66a848689417ec8901a2500c to your computer and use it in GitHub Desktop.
Hook Validation for React
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 {useRef} from 'react'; | |
/* Usage | |
const [user, setUser] = useState({ | |
username: '', | |
password: '', | |
}); | |
const [isUsernameInvalid, usernameErrors] = useValidate(user.username, [isEmpty]); | |
const [isPasswordInvalid, passwordErrors] = useValidate(user.password, [isEmpty]); | |
<Button | |
disabled={isUsernameInvalid} | |
> | |
{'Login'} | |
</Button> | |
*/ | |
const useValidate = ( | |
value = '', | |
validations: ((value: string) => boolean | string)[] | |
): [boolean, string[]] => { | |
const errors: string[] = []; | |
const init = useRef(false); /* When tests run for the first time do not run the tests */ | |
const setInit = (initValue: boolean) => { | |
init.current = initValue; | |
}; | |
if (value.length) setInit(true); | |
if (!init.current) { | |
return [true, []]; | |
} | |
for (const validation of validations) { | |
const check = validation(value); | |
if (typeof check === 'string') errors.push(check); | |
} | |
return [!!errors.length, errors]; | |
}; | |
export * from './validators'; | |
export default useValidate; |
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
export const isEmpty = (value: string) => | |
!value && 'This field is mandatory'; | |
export const isEqualWith = | |
(valueToCheckWith: string) => (currentValue: string) => | |
currentValue !== valueToCheckWith && 'Fields are not equal'; | |
export const isValidIpv4 = (value: string) => { | |
const ipRegex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/g; | |
return !ipRegex.test( | |
value | |
) && 'This is not a valid ip v4'; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment