Ott 168 login validation errors (#41)
parent
c23e650512
commit
2bdde0a79a
@ -1,26 +1,68 @@ |
||||
import type { FormEvent } from 'react' |
||||
import type { FormEvent, FocusEvent } from 'react' |
||||
|
||||
import trim from 'lodash/trim' |
||||
import isEmpty from 'lodash/isEmpty' |
||||
|
||||
import { useAuthStore } from 'features/AuthStore' |
||||
import { useForm } from 'features/FormStore' |
||||
import { formIds } from 'features/Register/components/RegistrationStep/config' |
||||
import { isValidEmail } from 'features/Register/helpers/isValidEmail' |
||||
|
||||
const readFormValue = (event: FormEvent<HTMLFormElement>) => ( |
||||
(fieldName: string) => trim(event.currentTarget[fieldName]?.value) |
||||
) |
||||
|
||||
export const useForm = () => { |
||||
export const useLoginForm = () => { |
||||
const { |
||||
readFormError, |
||||
readFormValue, |
||||
updateFormError, |
||||
updateFormValue, |
||||
} = useForm() |
||||
const { login } = useAuthStore() |
||||
|
||||
const onEmailBlur = ({ target }: FocusEvent<HTMLInputElement>) => { |
||||
if (!isValidEmail(target.value)) { |
||||
updateFormError(formIds.email, 'error_invalid_email_format') |
||||
} |
||||
} |
||||
|
||||
const readTrimmedValue = (fieldName: string) => trim(readFormValue(fieldName)) |
||||
|
||||
const validateForm = () => { |
||||
let hasError = false |
||||
const email = readTrimmedValue(formIds.email) |
||||
const password = readTrimmedValue(formIds.password) |
||||
if (isEmpty(email)) { |
||||
updateFormError(formIds.email, 'error_empty_email') |
||||
hasError = true |
||||
} else if (!isValidEmail(email)) { |
||||
updateFormError(formIds.email, 'error_invalid_email_format') |
||||
hasError = true |
||||
} |
||||
if (isEmpty(password)) { |
||||
updateFormError(formIds.password, 'error_empty_password') |
||||
hasError = true |
||||
} |
||||
return !hasError |
||||
} |
||||
|
||||
const onError = (message: string) => { |
||||
updateFormError(formIds.formError, message) |
||||
} |
||||
|
||||
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => { |
||||
event.preventDefault() |
||||
|
||||
const readFieldValue = readFormValue(event) |
||||
const email = readFieldValue(formIds.email) |
||||
const password = readFieldValue(formIds.password) |
||||
if (validateForm()) { |
||||
const email = readTrimmedValue(formIds.email) |
||||
const password = readTrimmedValue(formIds.password) |
||||
|
||||
login({ email, password }) |
||||
login({ email, password }).catch(onError) |
||||
} |
||||
} |
||||
|
||||
return { handleSubmit } |
||||
return { |
||||
handleSubmit, |
||||
onEmailBlur, |
||||
readFormError, |
||||
readFormValue, |
||||
updateFormValue, |
||||
} |
||||
} |
||||
|
||||
Loading…
Reference in new issue