By the end of this lesson, you will understand how to show helpful validation messages in forms using JavaScript.
Validation messages help users by providing feedback on their input. For example, if you fill out a form with incorrect email format, the app should tell you. This makes it easier to fill out forms correctly.
File: form-validation.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
</head>
<body>
<form id="myForm">
<label for="email">Email:</label>
<input type="text" id="email" name="email" required>
<span id="message" style="color: red;">< /span>
<br>
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById('myForm');
const emailInput = document.getElementById('email');
const message = document.getElementById('message');
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission
const emailValue = emailInput.value;
if (!validateEmail(emailValue)) {
message.textContent = 'Please enter a valid email.';
} else {
message.textContent = 'Email is valid!';
}
});
function validateEmail(email) {
const regex = /^[^s@]+@[^s@]+.[^s@]+$/;
return regex.test(email);
}
</script>
</body>
</html>
Expected Output:
When you enter a valid email, the message will say "Email is valid!".
If you enter an invalid email, the message will say "Please enter a valid email.".
The code sets up a simple form that asks for an email. When the user hits submit, it checks if the email format is correct using a regular expression. If the format is wrong, it shows a helpful message.
Now, create a form that checks if a user’s name is filled in. If not, show a message saying, “Name cannot be empty!”.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Name Validation</title>
</head>
<body>
<form id="nameForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<span id="nameMessage" style="color: red;">< /span>
<br>
<button type="submit">Submit</button>
</form>
<script>
const nameForm = document.getElementById('nameForm');
const nameInput = document.getElementById('name');
const nameMessage = document.getElementById('nameMessage');
nameForm.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission
const nameValue = nameInput.value;
if (nameValue.trim() === '') {
nameMessage.textContent = 'Name cannot be empty!';
} else {
nameMessage.textContent = 'Name is valid!';
}
});
</script>
</body>
</html>