Solution Files
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exercise 6 - User Profile</title>
</head>
<body>
<h1>Exercise 6: User Profile - Input and Validation</h1>
<script src="script.js"></script>
</body>
</html>
script.js
// Get user inputs
let firstName = prompt("Enter your first name:");
let ageInput = prompt("Enter your age:");
let email = prompt("Enter your email address:");
let isStudentInput = prompt("Are you a student? (yes/no):");
// Convert and validate age
let age = Number(ageInput);
let isAgeValid = !isNaN(age) && age > 0;
// Validate student response
let isStudentValid = false;
let isStudent = false;
if (isStudentInput !== null) {
let studentResponse = isStudentInput.toLowerCase();
if (studentResponse === 'yes' || studentResponse === 'no') {
isStudentValid = true;
isStudent = studentResponse === 'yes';
}
}
// Validate email
let isEmailValid = email !== null && email.includes('@');
// Validate name
let isNameValid = firstName !== null && firstName.trim() !== '';
// Display results
document.write("<h2>User Profile:</h2>");
if (!isNameValid) {
document.write("<p style='color: red;'><strong>Error:</strong> Please enter a valid name.</p>");
} else if (!isAgeValid) {
document.write("<p style='color: red;'><strong>Error:</strong> Please enter a valid age (must be a positive number).</p>");
} else if (!isEmailValid) {
document.write("<p style='color: red;'><strong>Error:</strong> Please enter a valid email address (must contain '@').</p>");
} else if (!isStudentValid) {
document.write("<p style='color: red;'><strong>Error:</strong> Please answer 'yes' or 'no' for the student question.</p>");
} else {
// All validations passed - display profile
document.write(`<p><strong>Name:</strong> ${firstName}</p>`);
document.write(`<p><strong>Age:</strong> ${age}</p>`);
document.write(`<p><strong>Email:</strong> ${email}</p>`);
document.write(`<p><strong>Student:</strong> ${isStudent ? 'Yes' : 'No'}</p>`);
}