Checking form data in the browser gives users instant feedback.
Steps
- Listen to the form's
submitevent - Call
e.preventDefault()to stop sending - Read values with
input.value.trim() - Check each rule and show messages
- If everything is fine, send the form (or the data)
Useful checks
- Required:
value === '' - Length:
value.length < 3 - Email:
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) - Indian mobile:
/^[6-9]\d{9}$/.test(value)
Important
Browser validation is for user experience only. Always validate again on the server (PHP/Laravel), because anyone can bypass JavaScript.
Example
Example — Validate a sign-up form
HTML
<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>