Created
June 7, 2020 09:12
-
-
Save N-Porsh/5155210bc9213df4caa9789b40c9367c to your computer and use it in GitHub Desktop.
Vanilla JS Reset-form validation
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
(function () { | |
let password = document.getElementById("password"); | |
let confirmPass = document.getElementById("confirm_password"); | |
let submit = document.getElementById("submit"); | |
function isPasswordStrong() { | |
const pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/g; | |
return pattern.test(password.value); | |
} | |
function samePassword() { | |
return password.value === confirmPass.value; | |
} | |
function PasswordStrength() { | |
if (isPasswordStrong()) { | |
password.nextElementSibling.style.display = 'none'; | |
} else { | |
password.nextElementSibling.style.display = ''; | |
} | |
} | |
function PasswordMatch() { | |
if (samePassword()) { | |
confirmPass.nextElementSibling.style.display = 'none'; | |
} else { | |
confirmPass.nextElementSibling.style.display = ''; | |
} | |
} | |
function canSubmit() { | |
return samePassword() && isPasswordStrong(); | |
} | |
function enableSubmitButton() { | |
submit.disabled = !canSubmit(); | |
} | |
// disable button by default | |
enableSubmitButton(); | |
password.onkeyup = function () { | |
PasswordStrength(); | |
PasswordMatch(); | |
enableSubmitButton(); | |
}; | |
confirmPass.onfocus = PasswordMatch; | |
confirmPass.onkeyup = function () { | |
PasswordMatch(); | |
enableSubmitButton(); | |
}; | |
submit.onclick = function (e) { | |
e.preventDefault(); | |
const queryString = window.location.search; | |
const urlParams = new URLSearchParams(queryString); | |
const token = urlParams.get('token'); | |
fetch('/auth/change-password', { | |
headers: { | |
'Authorization': 'Bearer ' + token, | |
"Content-Type": "application/json; charset=utf-8" | |
}, | |
method: 'POST', | |
body: JSON.stringify({ | |
password: password.value, | |
}) | |
}) | |
.then(function (response) { | |
return response.json(); | |
}) | |
.then(function (data) { | |
let status = document.getElementById('status'); | |
if (data.hasOwnProperty('errorCode')) { | |
status.className = "fail"; | |
status.innerText = "Something went wrong: " + data.message; | |
} else { | |
status.className = "success"; | |
status.innerHTML = "Password successfully changed"; | |
} | |
}) | |
.catch(function (err) { | |
console.log("Error: ", err); | |
}) | |
}; | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment