MSc(CS) FSD-I Practical 1-Student Registration details
Students Create an HTML form that contain the Student Registration details and write a JavaScript to validate Student first and last name as it should not contain other than alphabets and age should be between 18 to 50.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Registration Form</title>
<script>
// ES6 function to validate form fields
const validateForm = () => {
let isValid = true;
// Get input values
const firstName = document.getElementById('firstName').value.trim();
const lastName = document.getElementById('lastName').value.trim();
const age = document.getElementById('age').value.trim();
// Get error elements
const firstNameError = document.getElementById('firstNameError');
const lastNameError = document.getElementById('lastNameError');
const ageError = document.getElementById('ageError');
// Reset errors
firstNameError.textContent = '';
lastNameError.textContent = '';
ageError.textContent = '';
// Regular Expression
let reF=/^[A-Za-z]+$/;
// Validate first name using regular expression (only alphabets)
if (!reF.test(firstName)) {
firstNameError.textContent = 'First name should only contain alphabets.';
isValid = false;
}
// Validate last name using regular expression (only alphabets)
if (!reF.test(lastName)) {
lastNameError.textContent = 'Last name should only contain alphabets.';
isValid = false;
}
// Validate age (between 18 and 50)
if (!age || age < 18 || age > 50) {
ageError.textContent = 'Age must be between 18 and 50.';
isValid = false;
}
// If all validations pass, show success message
if (isValid) {
alert('Registration successful!');
document.getElementById('registrationForm').reset(); // Clear the form
}
};
</script>
</head>
<body>
<h2>Student Registration</h2>
<form id="registrationForm">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" placeholder="Enter your first name">
<span id="firstNameError"></span>
<br><br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" placeholder="Enter your last name">
<span id="lastNameError"></span>
<br><br>
<label for="age">Age:</label>
<input type="number" id="age" placeholder="Enter your age">
<span id="ageError"></span>
<br><br>
<button type="button" onclick="validateForm()">Register</button>
</form>
</body>
</html>
Comments
Post a Comment