2080 3

BIT251 ยท 2080 ยท 10 marks

Create an HTML form for signup. The form should contain form elements for username, password, email, country, gender, and hobbies. The username should be at least of 8 length, password should be of 6 length having at least one digit. The username and password should be present. The email should be v

Create an HTML form for signup. The form should contain form elements for username, password, email, country, gender, and hobbies. The username should be at least of 8 length, password should be of 6 length having at least one digit. The username and password should be present. The email should be valid. The country field in dropdown should be selected. The gender and hobbies in radio and checkboxes should also be checked respectively. Now write JavaScript function to validate the form as per mentioned.[10]

Web Technology IChapter 8: JavaScript Events and Form ValidationForm validation concept and purpose

Quick answer

Radio buttons and checkboxes share a name rather than an id, which is why they are read with getElementsByName() and scanned in a loop, while single-valued controls are read directly by id.

HTML Form with JavaScript Validation

Complete Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Signup Form</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 500px;
            margin: 40px auto;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 8px;
        }
        h2 {
            text-align: center;
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            font-weight: bold;
            margin-bottom: 5px;
        }
        input[type="text"],
        input[type="password"],
        input[type="email"],
        select {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
            border: 1px solid #aaa;
            border-radius: 4px;
        }
        .error {
            color: red;
            font-size: 13px;
            margin-top: 4px;
        }
        input[type="submit"] {
            width: 100%;
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>

<h2>Signup Form</h2>

<form name="signupForm" onsubmit="return validateForm()">

    <!-- Username -->
    <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" placeholder="Enter username">
        <span class="error" id="usernameError"></span>
    </div>

    <!-- Password -->
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" placeholder="Enter password">
        <span class="error" id="passwordError"></span>
    </div>

    <!-- Email -->
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" placeholder="Enter email">
        <span class="error" id="emailError"></span>
    </div>

    <!-- Country -->
    <div class="form-group">
        <label for="country">Country:</label>
        <select id="country" name="country">
            <option value="">-- Select Country --</option>
            <option value="nepal">Nepal</option>
            <option value="india">India</option>
            <option value="usa">USA</option>
            <option value="uk">UK</option>
            <option value="australia">Australia</option>
        </select>
        <span class="error" id="countryError"></span>
    </div>

    <!-- Gender -->
    <div class="form-group">
        <label>Gender:</label>
        <input type="radio" name="gender" value="male"> Male
        <input type="radio" name="gender" value="female"> Female
        <input type="radio" name="gender" value="other"> Other
        <span class="error" id="genderError"></span>
    </div>

    <!-- Hobbies -->
    <div class="form-group">
        <label>Hobbies:</label>
        <input type="checkbox" name="hobbies" value="reading"> Reading
        <input type="checkbox" name="hobbies" value="gaming"> Gaming
        <input type="checkbox" name="hobbies" value="travelling"> Travelling
        <input type="checkbox" name="hobbies" value="cooking"> Cooking
        <span class="error" id="hobbiesError"></span>
    </div>

    <!-- Submit -->
    <div class="form-group">
        <input type="submit" value="Sign Up">
    </div>

</form>

<script>
    function validateForm() {

        // Clear all previous error messages
        var errorIds = [
            "usernameError", "passwordError", "emailError",
            "countryError", "genderError", "hobbiesError"
        ];
        for (var i = 0; i < errorIds.length; i++) {
            document.getElementById(errorIds[i]).innerText = "";
        }

        var isValid = true;

        // ---- 1. Username Validation ----
        var username = document.getElementById("username").value.trim();

        if (username === "") {
            document.getElementById("usernameError").innerText
                = "Username is required.";
            isValid = false;
        } else if (username.length < 8) {
            document.getElementById("usernameError").innerText
                = "Username must be at least 8 characters long.";
            isValid = false;
        }

        // ---- 2. Password Validation ----
        var password = document.getElementById("password").value.trim();
        var hasDigit = /\d/;  // Regular expression to check for at least one digit

        if (password === "") {
            document.getElementById("passwordError").innerText
                = "Password is required.";
            isValid = false;
        } else if (password.length < 6) {
            document.getElementById("passwordError").innerText
                = "Password must be at least 6 characters long.";
            isValid = false;
        } else if (!hasDigit.test(password)) {
            document.getElementById("passwordError").innerText
                = "Password must contain at least one digit.";
            isValid = false;
        }

        // ---- 3. Email Validation ----
        var email = document.getElementById("email").value.trim();
        var emailPattern = /^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

        if (email === "") {
            document.getElementById("emailError").innerText
                = "Email is required.";
            isValid = false;
        } else if (!emailPattern.test(email)) {
            document.getElementById("emailError").innerText
                = "Please enter a valid email address.";
            isValid = false;
        }

        // ---- 4. Country Validation (dropdown) ----
        var country = document.getElementById("country").value;

        if (country === "") {
            document.getElementById("countryError").innerText
                = "Please select a country.";
            isValid = false;
        }

        // ---- 5. Gender Validation (radio buttons) ----
        var genders = document.getElementsByName("gender");
        var genderChosen = false;
        for (var g = 0; g < genders.length; g++) {
            if (genders[g].checked) {
                genderChosen = true;
                break;
            }
        }
        if (!genderChosen) {
            document.getElementById("genderError").innerText
                = "Please select your gender.";
            isValid = false;
        }

        // ---- 6. Hobbies Validation (checkboxes) ----
        var hobbies = document.getElementsByName("hobbies");
        var hobbyCount = 0;
        for (var h = 0; h < hobbies.length; h++) {
            if (hobbies[h].checked) {
                hobbyCount++;
            }
        }
        if (hobbyCount === 0) {
            document.getElementById("hobbiesError").innerText
                = "Please select at least one hobby.";
            isValid = false;
        }

        // ---- Final result ----
        if (isValid) {
            alert("Signup successful.");
        }

        // false prevents submission, true allows it
        return isValid;
    }
</script>

</body>
</html>

How Each Element is Validated

ElementTypeHow the value is readRule
UsernameText boxgetElementById("username").valueRequired, at least 8 characters
PasswordPassword boxgetElementById("password").valueRequired, at least 6 characters, must contain a digit
EmailEmail boxgetElementById("email").valueRequired, must match the email pattern
CountryDropdowngetElementById("country").valueMust not be the empty placeholder option
GenderRadio groupgetElementsByName("gender")Exactly one button must be checked
HobbiesCheckbox groupgetElementsByName("hobbies")At least one box must be checked

Conclusion

The function clears the old messages first, then tests every control and records failures in a single isValid flag instead of returning early, so the user sees all the problems in one pass. Returning false from onsubmit cancels the submission. This client-side check gives instant feedback, but the same rules must be repeated on the server because JavaScript can be disabled or bypassed.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.