To help you get your JavaScript validation running, please provide the specific code or describe what the validation is supposed to do. Here are some general steps to ensure basic JavaScript form validation works:
Html :
<form id="myForm">
<input type="text" id="username" name="username" required>
<input type="email" id="email" name="email" required>
<input type="submit" value="Submit">
</form>
<div id="error-message"></div>
JavaScript Validation:
document.getElementById('myForm').addEventListener('submit', function(event) {
const username = document.getElementById('username').value;
const email = document.getElementById('email').value;
const errorMessage = document.getElementById('error-message');
errorMessage.innerHTML = '';
if (username === '') {
errorMessage.innerHTML = 'Username is required.';
event.preventDefault();
} else if (!validateEmail(email)) {
errorMessage.innerHTML = 'Invalid email address.';
event.preventDefault();
}
});
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(String(email).toLowerCase());
}
- HTML: A simple form with
required
attributes and a placeholder for error messages. - JavaScript:
- An event listener for form submission.
- Basic validation checks for the username and email fields.
- Prevents form submission (
event.preventDefault()
) if validation fails.
Make sure your JavaScript is correctly linked in your HTML, and check the console for any errors.
Leave a Reply