85 lines
2.6 KiB
JavaScript
85 lines
2.6 KiB
JavaScript
|
|
const $form = document.querySelector(".form")
|
|
|
|
const $validationBox = document.querySelector("#validationBox")
|
|
const $validationMsg = document.querySelector("#validationMsg")
|
|
|
|
const $successBox = document.querySelector("#successBox")
|
|
const $successMsg = document.querySelector("#successMsg")
|
|
|
|
const showError = (message) => {
|
|
$validationBox.style.display = "block"
|
|
$validationMsg.innerText = message
|
|
}
|
|
|
|
const clearError = () => {
|
|
$validationMsg.innerText = ""
|
|
$validationBox.style.display = "none"
|
|
}
|
|
|
|
const showSuccess = (message) => {
|
|
$successBox.style.display = "block"
|
|
$successMsg.innerText = message
|
|
}
|
|
|
|
const clearSuccess = () => {
|
|
$successMsg.innerText = ""
|
|
$successBox.style.display = "none"
|
|
}
|
|
|
|
document.addEventListener("DOMContentLoaded", (e) => {
|
|
$form.addEventListener("submit", async (e) => {
|
|
e.preventDefault()
|
|
|
|
clearError()
|
|
clearSuccess()
|
|
|
|
const formData = new FormData($form)
|
|
const data = Object.fromEntries(formData)
|
|
|
|
if ([{key: "full_name", name: "Full Name"}, {key: "email", name: "Email"}, {key: "password", name: "Password"}, {key: "repeat_password", name: "Password"}].some(({key, name}) => {
|
|
if (!data[key]) {
|
|
showError(`${name} is required`)
|
|
return true
|
|
}
|
|
return false;
|
|
})) {
|
|
return
|
|
}
|
|
|
|
if (data.repeat_password != data.password) {
|
|
console.log("passwords do not match")
|
|
showError("Password does not match")
|
|
return
|
|
}
|
|
|
|
if (data.terms_and_conditions !== "on") {
|
|
console.log("terms and conditions are not accepted")
|
|
showError("Terms and Conditions are not accepted. Cannot proceed without agreement")
|
|
return
|
|
}
|
|
|
|
try {
|
|
const response = await fetch("/api/v1/register", {
|
|
method: "POST",
|
|
body: JSON.stringify(data),
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
})
|
|
if (response.status != 200) {
|
|
const json = await response.json()
|
|
const text = json.error || "Unexpected error happened"
|
|
showError(`Failed to create an account. ${text[0].toUpperCase() + text.slice(1)}`)
|
|
} else {
|
|
showSuccess("Account has been created. You can now log into your new account")
|
|
$form.reset()
|
|
}
|
|
} catch(err) {
|
|
showError("Failed to create account. Unexpected error happened")
|
|
}
|
|
})
|
|
})
|
|
|
|
|