|
| 1 | +const form = document.getElementById("form"); |
| 2 | +const username = document.getElementById("username"); |
| 3 | +const email = document.getElementById("email"); |
| 4 | +const password = document.getElementById("password"); |
| 5 | +const password2 = document.getElementById("password2"); |
| 6 | + |
| 7 | +function showError(input, message) { |
| 8 | + const formControl = input.parentElement; |
| 9 | + formControl.className = "form-control error"; |
| 10 | + const small = formControl.querySelector("small"); |
| 11 | + small.innerText = message; |
| 12 | +} |
| 13 | + |
| 14 | +function showSuccess(input, message) { |
| 15 | + const formControl = input.parentElement; |
| 16 | + formControl.className = "form-control success"; |
| 17 | +} |
| 18 | + |
| 19 | +function getFieldName(input) { |
| 20 | + return input.id.charAt(0).toUpperCase() + input.id.slice(1); |
| 21 | +} |
| 22 | + |
| 23 | +function checkRequired(inputs) { |
| 24 | + inputs.forEach((input) => { |
| 25 | + if (input.value.trim() === "") { |
| 26 | + showError(input, `${getFieldName(input)} is required`); |
| 27 | + } else { |
| 28 | + showSuccess(input); |
| 29 | + } |
| 30 | + }); |
| 31 | +} |
| 32 | + |
| 33 | +function checkLength(input, min, max) { |
| 34 | + if (input.value.length < min) { |
| 35 | + showError( |
| 36 | + input, |
| 37 | + `${getFieldName(input)} must be at least ${min} characters` |
| 38 | + ); |
| 39 | + } else if (input.value.length > max) { |
| 40 | + showError( |
| 41 | + input, |
| 42 | + `${getFieldName(input)} must be less than ${max} characters` |
| 43 | + ); |
| 44 | + } else { |
| 45 | + showSuccess(input); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +function checkEmail(input) { |
| 50 | + // Reference: https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript |
| 51 | + const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; |
| 52 | + if (re.test(String(input.value.trim()).toLowerCase())) showSuccess(input); |
| 53 | + else showError(input, `${getFieldName(input)} is not valid`); |
| 54 | +} |
| 55 | + |
| 56 | +function checkPasswordMatch(input1, input2) { |
| 57 | + if (input1.value !== input2.value) { |
| 58 | + showError(input2, "Passwords do not match"); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +form.addEventListener("submit", (e) => { |
| 63 | + e.preventDefault(); |
| 64 | + checkRequired([username, email, password, password2]); |
| 65 | + checkLength(username, 3, 15); |
| 66 | + checkLength(password, 6, 25); |
| 67 | + checkEmail(email); |
| 68 | + checkPasswordMatch(password, password2); |
| 69 | +}); |
0 commit comments