By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Form Validation (task with DOM and jQuery)

+1 vote

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.


form validation screenshot 1

form validation screenshot 2

asked in JavaScript category by user richard8502

1 Answer

0 votes
  • 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">
    <meta charset="UTF-8">
    <title>Form Validation</title>
    <link rel="stylesheet" href="style.css">
    <script src=""
<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 class="pairContainer">
                <label for="email">Email:</label>
                <input id="email" type="text">
            <div class="pairContainer">
                <label for="password">Password:</label>
                <input id="password" type="password">
            <div class="pairContainer">
                <label for="confirm-password">Confirm Password:</label>
                <input id="confirm-password" type="password">
            <div class="pairContainer">
                <label for="company">Is Company?</label>
                <input id="company" type="checkbox">
        <fieldset id="companyInfo" style="display: none;">
            <legend>Company Informaion:</legend>
            <div class="pairContainer">
                <label for="companyNumber">Company Number</label>
                <input id="companyNumber" type="number">
        <button id="submit">Submit</button>
    <div id="valid" style="display: none">Valid</div>
<script src="formValidation.js"></script>
    window.onload = function () {

CSS code:

    width: 410px;

    box-sizing: border-box;
    background-image: url("images/background3.jpg");
    width: 420px;
    padding: 5px;

    width: 95%;
    display: table;
    margin: 10px 0;

    width: 60%;

label, legend{
    color: darkblue;
    font-weight: bold;

    box-sizing: border-box;
    font-weight: bold;
    margin: 5px auto;
    width: 95%;
    background-color: blue;
    display: block;

    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 (':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)

        if (isValid) {
            validDiv.css('display', 'block');
        } else {
            validDiv.css('display', 'none');

    function validateForm() {
        isValid = true;

        if (':checked')) {

        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;


answered by user matthew44