Validating User Input
Form validation ensures users enter correct and complete information before submitting data to a server.
JavaScript allows you to validate forms on the client-side, providing immediate feedback and preventing invalid submissions.
Proper validation improves user experience and reduces server load by catching errors before data is sent.
// Basic form validation
function validateForm() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const age = document.getElementById('age').value;
// Check if fields are empty
if (name === '' || email === '' || age === '') {
alert('All fields are required!');
return false;
}
// Validate email format
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
alert('Please enter a valid email!');
return false;
}
// Validate age is a number
if (isNaN(age) || age < 1 || age > 120) {
alert('Please enter a valid age!');
return false;
}
return true; // Form is valid
}
// Attach to form submit
document.getElementById('myForm').addEventListener('submit', function(event) {
if (!validateForm()) {
event.preventDefault(); // Stop submission
}
});
- Required Fields - Check if fields are not empty
- Email Validation - Use regex patterns to verify format
- Number Validation - Check if input is numeric and within range
- Length Validation - Ensure minimum/maximum character limits
- Pattern Matching - Use regular expressions for complex validation
- Real-time Validation - Validate as user types using input events
- Custom Error Messages - Provide clear, specific feedback
Try Form Validation
<form id="registrationForm">
<div class="form-group">
<label>Username (3-15 characters):</label>
<input type="text" id="username" placeholder="Enter username">
<span class="error" id="usernameError"></span>
</div>
<div class="form-group">
<label>Email:</label>
<input type="text" id="email" placeholder="Enter email">
<span class="error" id="emailError"></span>
</div>
<div class="form-group">
<label>Password (min 6 characters):</label>
<input type="password" id="password" placeholder="Enter password">
<span class="error" id="passwordError"></span>
</div>
<div class="form-group">
<label>Age:</label>
<input type="number" id="age" placeholder="Enter age">
<span class="error" id="ageError"></span>
</div>
<button type="submit">Register</button>
<div id="successMessage"></div>
</form>
Note: Client-Side Only: Always validate on the server too! Client-side validation can be bypassed.
Note: User Experience: Show validation errors after user finishes typing (blur event) rather than on every keystroke.
Note: Accessibility: Use proper labels, aria attributes, and ensure error messages are announced to screen readers.