Web Technology - Old Questions

2. Write HTML Script for creating a form containing text box for username, password field for password, and checkbox for Education fields. Write a JavaScript function for the validation of the form for all of the fields as required. In addition length of username should at least 4, the password should start with digit and end with $.

10 marks | Asked in Model Question

// index.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="form.css">

    <title>Form</title>

    <script type="text/javascript" src="validate.js"></script>

</head>

<body>  

    <div class="form">

<h2>Enter Details</h2>

        <form action=" " onsubmit="return validate()">

            User Name: <input id="uname" type="text" name="username" required><br><br>

            Password: <input id="upass" type="password" name="password" required><br><br>

            Education Field: 

            <input type="checkbox" name="field[]" value="csit"> BscCSIT

            <input type="checkbox" name="field[]" value="bca"> BCA

            <input type="checkbox" name="field[]" value="bit"> BIT <br><br>

            <button  type="submit">Submit</button>

        </form>

    </div>

</body>

</html>

// form.css

body{

    margin: 0;

    padding:0;

    background-image: url(form.jpg);

    background-repeat: no-repeat;

    background-size: cover;

}

.form {

padding: 20% 40%; 

}

// validate.js

function validate(){

    var username = document.getElementById('uname');

    if(username.value.trim().length < 4 ){

        username.style.border = "solid 1px red";

        alert("Username Should Be at least 4");

        return false;

    }

    const password = document.getElementById('upass');

    var regx = /[0-9][a-zA-Z0-9]*[a-zA-Z0-9][$]/;

    if(!regx.test(password.value)){

        password.style.border = 'solid 1px red';

        alert("Password should start with digit and end with $");

        return false;

    }

    var education = document.getElementsByName('field[]');

    for(var i=0;i<education.length;i++){

        if(education[i].checked){

           continue;

        }

        alert("Please Select Your educational field.")

        return false;

    }

   return true;

}