Anna University Regional Campus, Coimbatore

Department of Computer Science and Engineering

Experiment 3 - Client-Side Scripts for Validating Web Form Control using DHTML


AIM:

To develop a program for validating web form controls using DHTML.

ALGORITHM:

  1. Start the program.
  2. Define the title within the <title> tag.
  3. Include the script within <script> tag for form validation.
  4. Validate each form field using conditions.
  5. If a field is empty or invalid, show an error message.
  6. If all fields are valid, display a success message.
  7. Design the form with GUI elements.
  8. Test all buttons for correct functionality.
  9. End the program.

PROGRAM:

Registration Form Validation (validateForm.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Registration Form</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Registration Form</h1>
    <form id="registrationForm" onsubmit="return validateForm()">
        <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" id="name">
            <span class="error" id="nameError">* Required</span>
        </div>
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="email">
            <span class="error" id="emailError">* Invalid email</span>
        </div>
        <input type="submit" value="Submit">
    </form>
    <script>
        function validateForm() {
            let isValid = true;
            const name = document.getElementById("name").value.trim();
            const email = document.getElementById("email").value.trim();

            // Name validation
            if (!name) {
                document.getElementById("nameError").style.display = "inline";
                isValid = false;
            } else {
                document.getElementById("nameError").style.display = "none";
            }

            // Email validation
            const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
            if (!emailRegex.test(email)) {
                document.getElementById("emailError").style.display = "inline";
                isValid = false;
            } else {
                document.getElementById("emailError").style.display = "none";
            }

            if (isValid) {
                alert("Registration Successful!");
            }
            return isValid;
        }
    </script>
</body>
</html>
            

Sample Output:

Output Image 1 Output Image 2

RESULT:

Thus, a program to validate a registration form using client-side scripts in DHTML was successfully created and tested.