Agyan
adda
Run
Reset
Copy
JavaScript Tutorial › JS Form Validation › Validate a sign-up form
Back to tutorial
Code
Edit, then press Run or Ctrl+Enter
<style> .err { color: crimson; font-size: 13px; display: block; } input { display: block; margin-top: 8px; padding: 6px; } </style> <form id="signup" novalidate> <input id="name" placeholder="Name"><span class="err" id="nameErr"></span> <input id="email" placeholder="Email"><span class="err" id="emailErr"></span> <input id="mobile" placeholder="Mobile"><span class="err" id="mobileErr"></span> <button>Sign up</button> </form> <p id="ok" style="color:green"></p> <script> document.getElementById('signup').addEventListener('submit', e => { e.preventDefault(); const val = id => document.getElementById(id).value.trim(); const show = (id, msg) => document.getElementById(id).textContent = msg; let valid = true; if (val('name').length < 3) { show('nameErr', 'Name must be at least 3 letters'); valid = false; } else show('nameErr', ''); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val('email'))) { show('emailErr', 'Enter a valid email'); valid = false; } else show('emailErr', ''); if (!/^[6-9]\d{9}$/.test(val('mobile'))) { show('mobileErr', 'Enter a 10-digit mobile number'); valid = false; } else show('mobileErr', ''); document.getElementById('ok').textContent = valid ? 'All good! Form can be sent.' : ''; }); </script>
Result