Skip to content

Instantly share code, notes, and snippets.

@aliakakis
Created December 8, 2022 09:28
Show Gist options
  • Save aliakakis/6f7c675e66a848689417ec8901a2500c to your computer and use it in GitHub Desktop.
Save aliakakis/6f7c675e66a848689417ec8901a2500c to your computer and use it in GitHub Desktop.
Hook Validation for React
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;
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