Latest Post:
Loading...

FORM VALIDATION (HTML+ CSS+ JAVASCRIPT)


Show Form Code (VS Code Style)

Form Validation Code (VS Code Style)

<!-- HTML Document Start -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Validation</title>

    <!-- CSS Styling -->
    <style>
        /* Form styling */
        form {
            max-width: 400px;
            width: 100%;
            margin: 40px auto;
            background-color: #ffffff;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }

        /* Input fields */
        input[type="text"], input[type="email"], input[type="password"] {
            width: 100%;
            padding: 10px;
            margin-top: 6px;
            font-size: 16px;
            box-sizing: border-box;
        }

        /* Submit button */
        input[type="submit"] {
            width: 100%;
            padding: 12px;
            font-size: 18px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
        }
    </style>

    <!-- JavaScript Validation -->
    <script>
        function validate() {
            // Check if name is empty
            if (document.myForm.txtbox.value == "") {
                alert("Please provide your name");
                document.myForm.txtbox.focus();
                return false;
            }

            // Check if email is empty
            if (document.myForm.emailid.value == "") {
                alert("Please provide your email!");
                document.myForm.emailid.focus();
                return false;
            }

            // Check if password is empty
            if (document.myForm.password.value == "") {
                alert("Please provide your password!");
                document.myForm.password.focus();
                return false;
            }

            // Check if retype password is empty
            if (document.myForm.repassword.value == "") {
                alert("Please retype your password!");
                document.myForm.repassword.focus();
                return false;
            }

            // Check if passwords match
            if (document.myForm.password.value != document.myForm.repassword.value) {
                alert("Passwords do not match!");
                document.myForm.repassword.focus();
                return false;
            }

            // All validations passed
            return true;
        }
    </script>
</head>

<body>

<!-- Registration form -->
<form name="myForm" onsubmit="return validate()">
    <label>Name:</label>
<input type="text" name="txtbox">

<label>Email:</label>
<input type="email" name="emailid">

<label>Password:</label>
<input type="password" name="password">

<label>Retype Password:</label>
<input type="password" name="repassword">

<input type="submit" value="Submit"> </form> </body> </html>

Post a Comment