[Solved] Form Validation (task with DOM and jQuery)

  

3
Topic starter

You are given the task to write validation for the fields of a simple form.

HTML and JavaScript Code:

The validations should be as follows:

  • The username needs to be between 3 and 20 symbols inclusively and only letters and numbers are allowed.
  • The password and confirm-password must be between 5 and 15 inclusively symbols and only word characters are allowed (letters, numbers and _).
  • The inputs of the password and confirm-password field must match.
  • The email field must contain the “@” symbol and at least one "."(dot) after it.
  • If the "Is company?" checkbox is checked, the CompanyInfo fieldset should become visible and the Company Number field must also be validated, if it isn’t checked the Company fieldset should have the style "display: none;" and the value of the Company Number field shouldn’t matter.
  • The Company Number field must be a number between 1000 and 9999.

Every field with an incorrect value when the [Submit] button is pressed should have the following style applied border-color: red;, alternatively if it’s correct it should have style border: none;. If there are required fields with an incorrect value when the [Submit] button is pressed, the div with id="valid" should become hidden ("display: none;"), alternatively if all fields are correct the div should become visible.

Constraints: You are NOT allowed to change the HTML or CSS files provided.

Screenshots:

form validation screenshot 1

form validation screenshot 2

1 Answer
2
  • Use addEventListener() or jQuery’s on() function to attach an event listener for the "change" event to the checkbox.
  • All buttons within a <form> automatically work as submit buttons, unless their type is manually assigned to something else, in order to avoid reloading the page upon clicking the [Submit] button you can add the following code in the function that handles the on click event.
  • The validation for the separate fields can be done using regex.

HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Validation</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"
            integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="
            crossorigin="anonymous"></script>
</head>
<body>
<div id="wrapper">
    <form id="registerForm">
        <fieldset id="userInfo">
            <legend>User Information:</legend>
            <div class="pairContainer">
                <label for="username">Userame:</label>
                <input id="username" type="text">
            </div>
            <div class="pairContainer">
                <label for="email">Email:</label>
                <input id="email" type="text">
            </div>
            <div class="pairContainer">
                <label for="password">Password:</label>
                <input id="password" type="password">
            </div>
            <div class="pairContainer">
                <label for="confirm-password">Confirm Password:</label>
                <input id="confirm-password" type="password">
            </div>
            <div class="pairContainer">
                <label for="company">Is Company?</label>
                <input id="company" type="checkbox">
            </div>
        </fieldset>
        <fieldset id="companyInfo" style="display: none;">
            <legend>Company Informaion:</legend>
            <div class="pairContainer">
                <label for="companyNumber">Company Number</label>
                <input id="companyNumber" type="number">
            </div>
        </fieldset>
        <button id="submit">Submit</button>
    </form>
    <div id="valid" style="display: none">Valid</div>
</div>
<script src="formValidation.js"></script>
<script>
    window.onload = function () {
        validate();
    }
</script>
</body>
</html>

CSS code:

#wrapper{
    margin:auto;
    width: 410px;
}
 
form{
    box-sizing: border-box;
    background-image: url("images/background3.jpg");
    width: 420px;
    padding: 5px;
}
 
.pairContainer{
    width: 95%;
    display: table;
    margin: 10px 0;
}
 
input{
    float:right;
    width: 60%;
}
 
label, legend{
    color: darkblue;
    font-weight: bold;
}
 
#submit{
    box-sizing: border-box;
    font-weight: bold;
    color:white;
    margin: 5px auto;
    width: 95%;
    background-color: blue;
    display: block;
}
 
#valid{
    box-sizing: border-box;
    width: 420px;
    padding: 5px;
    color: lime;
    border: 2px solid lime;
    text-align: center;
}

JavaScript with the jQuery solution inside:

function validate() {
    // get all html to jquery elements
    let username = $('#username'),
        email = $('#email'),
        password = $('#password'),
        confirmPassword = $('#confirm-password'),
        companyCheckbox = $('#company'),
 
        companyInfo = $('#companyInfo'),
        companyNumber = $('#companyNumber'),
 
        submitBtn = $('#submit'),
 
        validDiv = $('#valid');
 
    //set global valid
    let isValid = true;
 
    //checkbox make company div visible
    companyCheckbox.on("change", function () {
        if (companyCheckbox.is(':checked')) {
            companyInfo.css('display', 'block');
        } else {
            companyInfo.css('display', 'none');
        }
    });
 
    // validate all dislayed fields on submit
    submitBtn.on('click', function (ev) {
        //prevent default form behaviour (refresh page)
        ev.preventDefault();
        validateForm();
 
        if (isValid) {
            validDiv.css('display', 'block');
        } else {
            validDiv.css('display', 'none');
        }
    });
 
    function validateForm() {
        isValid = true;
 
        if (companyCheckbox.is(':checked')) {
            validateCompanyNumber();
        }
 
        validateInputWithRegex(username, /^[A-Za-z\d]{3,20}$/g);
        validateInputWithRegex(email, /^.*?@.*?\..*$/g);
 
        if (password.val() === confirmPassword.val()) {
            validateInputWithRegex(password, /^\w{5,15}$/g);
            validateInputWithRegex(confirmPassword, /^\w{5,15}$/g);
        } else {
            password.css('border', 'solid red');
            confirmPassword.css('border', 'solid red');
            isValid = false;
        }
    }
 
 
    function validateInputWithRegex(input, pattern) {
        if (pattern.test(input.val())) {
            input.css('border', 'none');
        } else {
            input.css('border', 'solid red');
            isValid = false;
        }
    }
 
    function validateCompanyNumber() {
        let numValue = +companyNumber.val();
        if (numValue >= 1000 && numValue <= 9999) {
            companyNumber.css('border', 'none');
        } else {
            companyNumber.css('border', 'solid red');
            isValid = false;
        }
    }
}
Share: