Sign Up Form

Sign Up

How do I get this js validation running?

1024 683 point-admin
  • 0



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());
}
  1. HTML: A simple form with required attributes and a placeholder for error messages.
  2. 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

Your email address will not be published.