Created
July 17, 2021 17:45
-
-
Save DZuz14/c5d7d43955699e5bdcadf87ed0ba8cc5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 React, { useState } from 'react' | |
/** | |
* @helpers | |
*/ | |
const isValidText = (str) => { | |
return /^[a-zA-Z\s]+$/.test(str) | |
} | |
const isValidEmail = (str) => { | |
return /^[^\s@]+@[^\s@]+$/.test(str) | |
} | |
const validateFields = (fields) => { | |
const errors = {} | |
for (const field of fields) { | |
if (field.value === '') { | |
errors[field.name] = EMPTY_FIELD | |
continue | |
} | |
if (field.type === 'text' && !isValidText(field.value)) { | |
errors[field.name] = NOT_VALID_TEXT | |
continue | |
} | |
if (field.type === 'email' && !isValidEmail(field.value)) { | |
errors[field.name] = INVALID_EMAIL_ADDRESS | |
continue | |
} | |
if (field.type === 'textarea' && field.value.length < 5) { | |
errors[field.name] = MESSAGE_TOO_SHORT | |
continue | |
} | |
} | |
return errors | |
} | |
/** | |
* @constants | |
*/ | |
const EMPTY_FIELD = 'This field must not be empty.' | |
const NOT_VALID_TEXT = 'Invalid text formatting.' | |
const INVALID_EMAIL_ADDRESS = 'Please enter a valid e-mail.' | |
const MESSAGE_TOO_SHORT = 'Message must be atleast 5 characters long.' | |
/** | |
* @ReactHook | |
*/ | |
const useFormValidationHook = (formData) => { | |
const [fields, setFieldsState] = useState(formData.fields) | |
const [errors, setErrors] = useState({}) | |
const [success, setSuccess] = useState(false) | |
const setFields = (e) => { | |
const name = e.target.getAttribute('name') | |
const value = e.target.value | |
setFieldsState((prev) => | |
prev.map((field) => { | |
if (field.name === name) return { ...field, value } | |
return field | |
}) | |
) | |
} | |
const handleSubmit = (e) => { | |
e.preventDefault() | |
setErrors({}) | |
const errors = validateFields(fields) | |
if (Object.keys(errors).length > 0) { | |
setErrors(errors) | |
} else { | |
setSuccess(formData.success) | |
} | |
} | |
return { fields, success, errors, handleSubmit, setFields } | |
} | |
export default useFormValidationHook |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment