In this tutorial, we will create simple form validation with javascript. You can use this tutorial as foundation to build more robust form validation. (we will be validating on Frontend only)
HTML
<div class="container"> <form class="signup_form"> <h1>Sign up for free</h1> <label>Full Name</label> <input type="text" placeholder="Full Name" data-field="fullname"> <span class="error hide">Cannot be empty</span> <label>Email</label> <input type="text" placeholder="Email address" data-field="email"> <span class="error hide">Invalid Email</span> <label>Password</label> <input type="password" placeholder="Pasword" data-field="password"> <span class="error hide">Must be minimum 6 characters</span> <button type="submit" value="Submit">Submit</button> </form> </div>
CSS
html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } body { margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; background-color: #ebf0f6; } .container { width: 450px; margin: 50px auto; display: flex; flex: column; align-items: center; background-color: #4152B3; border-radius: 9px; } .signup_form { width: 100%; padding: 0 25px; } .signup_form h1 { color: #fff; } input { display: block; width: 100%; padding: 15px; margin-bottom: 10px; border: 2px solid #ccc; border-radius: 5px; } ::placeholder { font-size: 16px; color: #000 } label { color: #fff; } button { width: 100%; padding: 15px; font-size: 18px; color: #fff; background-color: #7b96d4; border: none; border-radius: 5px; margin: 15px 0; cursor: pointer; } span { display: block; margin-top: -5px; margin-bottom: 5px; visibility: hidden; color: #fd557f; font-style: italic; } .displayError { visibility: visible; }
JS
const formDetail = document.querySelector('form'); const inputs = document.querySelectorAll('input'); formDetail.addEventListener('submit', formValidation); function formValidation(e) { e.preventDefault(); let errorCount = inputs.length; inputs.forEach(function (input) { let inputField = input.dataset.field if (input.value.length === 0) { input.style.borderColor = "#FC255A"; input.nextElementSibling.classList.add('displayError') } if (inputField === "fullname") { if (!input.value) { console.log(input) addError(input) } else { removeError(input); errorCount -= 1; } } if (inputField === "email") { let emailExp = /([A-Za-z0-9._-]+@[A-Za-z0-9._-]+\.[A-Za-z0-9]+)\w+/; let result = emailExp.test(input.value); if (!result) { addError(input) } else { removeError(input); errorCount -= 1; } } if (inputField === "password") { if (input.value.length < 6) { addError(input); } else { removeError(input); errorCount -= 1; } } }) if (errorCount == 0) { formDetail.submit(); } } function addError(e) { e.style.borderColor = "#FC255A"; e.nextElementSibling.classList.add('displayError') } function removeError(e) { e.style.borderColor = "#00A153"; e.nextElementSibling.classList.remove('displayError') }