Skip to content

Instantly share code, notes, and snippets.

@enmanuel97
Last active November 8, 2021 13:39
Show Gist options
  • Save enmanuel97/603a14fd6454592580b2b6e9d1e9a4db to your computer and use it in GitHub Desktop.
Save enmanuel97/603a14fd6454592580b2b6e9d1e9a4db to your computer and use it in GitHub Desktop.
useFormValidation
import { useState } from "react"
interface Validation {
[key: string]: {
required?: boolean;
minLength?: boolean;
maxLength?: boolean;
isEmail?: boolean;
isNumeric?: boolean;
}
}
export const useFormValidation = (state: any, formRules: Validation) => {
let initialStateErrors = Object.keys(state).reduce((acc, key) => {
return {
...acc,
[key]: false,
}
}, {});
const [stateErrors, setStateErrors] = useState(initialStateErrors);
const validate = (value: string, rules: Validation): any => {
let isInValid = false;
let errorMessage = '';
if (!rules) {
return false;
}
if (rules.required) {
isInValid = value.trim() === "";
errorMessage = 'This field is required';
return { isInValid, errorMessage };
}
if (rules.minLength) {
isInValid = value.length < rules.minLength;
errorMessage = `This field must be at least ${rules.minLength} characters`;
return { isInValid, errorMessage };
}
if (rules.maxLength) {
isInValid = value.length > rules.maxLength;
errorMessage = `This field must be at most ${rules.maxLength} characters`;
return { isInValid, errorMessage };
}
if (rules.isEmail) {
const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
isInValid = !pattern.test(value);
errorMessage = 'This field is invalid';
return { isInValid, errorMessage };
}
if (rules.isNumeric) {
const pattern = /^\d+$/;
isInValid = !pattern.test(value);
errorMessage = 'This field is invalid';
return { isInValid, errorMessage };
}
return { isInValid, errorMessage };
}
const handleChange = (e: any) => {
const { name, value } = e.target;
const rules = formRules[name];
const { isInValid } = validate(value, rules as Validation);
setStateErrors({
...stateErrors,
[name]: isInValid,
});
}
const handleSubmit = (e: any) => {
Object.keys(state).forEach(key => {
const rules = formRules[key];
const { isInValid, errorMessage } = validate(state[key], rules as Validation);
setStateErrors({
...stateErrors,
[key]: isInValid,
});
});
}
return {
handleChange,
handleSubmit,
stateErrors,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment