0

I have a small issue with my code not submitting my form. Once I fill out the form and press the submit button, nothing simply happens, it seems like the form is not being submitted. In practice, this code should check whether there are any empty fields and if so, it prompts a message instructing to fill out the fields. If every field filled out, submit the form.

            function storeUser() {
            var userObject = {};

            userObject.username = document.getElementById("username").value;
            userObject.email = document.getElementById("inputEmail").value;
            userObject.password = document.getElementById("inputPassword").value;
            userObject.passwordConfirm = document.getElementById("inputPasswordConfirm").value;
            userObject.mobileNumber = document.getElementById("inputNumber").value;
            userObject.score = 0;

            if (userObject.password !== userObject.passwordConfirm) {
                document.getElementById("Warning").innerHTML = "Your password doesn't match.";  
                return false;
            }

            if (userObject.username === "") {
                document.getElementById("Warning").innerHTML = "";
                document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
            } 
            if (userObject.email === " " ) {
                document.getElementById("Warning").innerHTML = "";
                document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
            } 
            if (userObject.password === " ") {
                document.getElementById("Warning").innerHTML = "";
                document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
            } 
            if (userObject.passwordConfirm === " ") {
                document.getElementById("Warning").innerHTML = "";
                document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
            } 
            if (userObject.mobileNumber === " ") {
                document.getElementById("Warning").innerHTML = "";
                document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
                return false;
            }
            else {
                return true;
            }

            localStorage[userObject.email] = JSON.stringify(userObject);

            document.getElementById("Result").innerHTML = "Success! You have registered your account.";

As you most probably noticed, I'm a complete novice to this. Aynone could lead me the right way?

EDIT:

                    <form class="form-container" name="registerForm" onsubmit="return false">
                    <p><b>Please fill out all fields to register your account</b></p>
                    <div class="form-group">
                        <input type="text" class="form-control" id="username" aria-describedby="username" placeholder="Username" minlength=3 required>
                    </div>

                    <div class="form-group">
                        <input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Enter email" required>
                    </div>

                    <div class="form-group">
                        <input type="password" class="form-control" id="inputPassword" placeholder="Password" required>
                    </div>

                    <div class="form-group">
                        <input type="password" class="form-control" id="inputPasswordConfirm" placeholder="Confirm password" required>
                    </div>

                    <div class="form-group">
                        <input type="tel" class="form-control" id="inputNumber" placeholder="Mobile number" pattern="^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$" required> 
                    </div>
                        <button type="submit" onclick="storeUser()" class="btn btn-primary regstrbtn">Register</button>
                        <p id="Result"></p>
                        <p id="Warning" style="color: red;"></p>
                </form>
4
  • Please add the markup for the form. Thanks. Commented Dec 7, 2019 at 20:50
  • Also worth noting: you don't need checks of the type if (userObject.username === ''), you can simply add the standalone attribute required to your <input>. Commented Dec 7, 2019 at 20:53
  • @RouninsaysJesuisMonica I would like to use both HTML 'required' tag and javascript. Commented Dec 7, 2019 at 21:48
  • In which case, do have a look at reportValidity() and the HTML5 Constraint Validation API Commented Dec 7, 2019 at 23:04

2 Answers 2

1

Looking at your code I found a number of problems:

  1. Invalid telephone number regexp: you are using the following regexp to validate the telephone number field, but it has a missing character:

    ^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$
    //               missing ] after 0-9 ^^
    

    (I am going to ignore the fact that the regular expression has placeholder 'Mobile number' yet only accepts landline phone numbers for inner and outer London in the UK.)

  2. You are showing validation error messages if the email, password, confirm-password and telephone number fields contain a single space:

     if (userObject.email === " " ) {
    

    You probably want to be comparing the values against an empty string instead:

     if (userObject.email === "" ) {
    
  3. The end of your storeUser() function is as follows:

        if (userObject.mobileNumber === " ") {
            document.getElementById("Warning").innerHTML = "";
            document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
            return false;
        }
        else {
            return true;
        }
    
        localStorage[userObject.email] = JSON.stringify(userObject);
    
        document.getElementById("Result").innerHTML = "Success! You have registered your account.";
    

    When do we reach the last two lines, the one that writes to local storage and the one that shows the success message?

    • If the telephone number field contains a single space, then a warning message appears and the function returns false.
    • If the telephone number field contains anything other than a single space, the function returns true.

    The last two lines are unreachable. They are never executed because the function returns before it gets to them.

    What you probably want to do is to get rid of the else clause and add return true; at the bottom, i.e.:

        if (userObject.mobileNumber === " ") {
            document.getElementById("Warning").innerHTML = "";
            document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
            return false;
        }
    
        localStorage[userObject.email] = JSON.stringify(userObject);
    
        document.getElementById("Result").innerHTML = "Success! You have registered your account.";
        return true;
    
  4. Inconsistent use of return false;. If the passwords don't match, or the telephone number field isn't filled out, the function returns false. There is no corresponding return false; line for the username, email, password and confirm-password fields. Add this line for each of these fields.

  5. You aren't clearing the warning message if the form is successfully completed. Add the line

    document.getElementById("Warning").innerHTML = "";
    

    to the end of your function.

    Incidentally you have various pairs of lines

            document.getElementById("Warning").innerHTML = "";
            document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
    

    but the first line in each pair is unnecessary because the empty-string value you assign to the inner HTML of the warning element is immediately replaced by the warning message assigned in the second line. You can delete the first line of each such pair.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your insight. Not only I managed to fix my form but also gained some new general knowledge.
0

You can simply manage this using HTML5 form field validators, please find below code snippet:

body {
    font-family: Helvetica, Arial;
    font-size:12px;
}
h1 {
    font-size:200%;
}
legend {
    padding:0 5px;
    text-align:right;
}
fieldset > div {
    margin:10px 0;
}
fieldset > legend + div {
    margin-top:0;
}
fieldset > div:last-child {
    margin-bottom:0;
}
label {
    display:inline-block;
    width:100px;
}
input {
    width:200px;
}
input[type="number"] {
    width:30px;
}
div > input[type="submit"] {
    background: #ccc;
    border:1px solid #999;
    width:auto;
}
input:required {
    background:hsl(180, 50%, 90%);
    border:1px solid #999;
}
input:optional {
    background:hsl(300, 50%, 90%);
    border:1px dotted hsl(180, 50%, 90%);
}
input:valid,
input:in-range {
    background:hsl(120, 50%, 90%);
    border-color:hsl(120, 50%, 50%);
}

input:invalid,
input:out-of-range {
    border-color:hsl(0, 50%, 50%);
    background:hsl(0, 50%, 90%);
}
.help {
    display:none;
    font-size:90%;
}
input:focus + .help {
    display:inline-block;
}
div.submit {
    margin-left:100px;
}
<form action="" method="post">
    <fieldset>
        <legend>Booking Details</legend>
        <div>
            <label for="name">Name:</label>
            <input id="name" name="name" value="" required  pattern="[A-Za-z-0-9]+\s[A-Za-z-'0-9]+" title="firstname lastname" aria-required="true" aria-describedby="name-format">
            <span id="name-format" class="help">Format: firstname lastname</span>
        </div>
        <div>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" value="" required aria-required="true">
        </div>
        <div>
            <label for="website">Website:</label>
            <input type="url" id="website" name="website" value="">
        </div>
        <div>
            <label for="numTickets"><abbr title="Number">No.</abbr> of Tickets:</label>
            <input type="number" id="numTickets" name="numTickets" value="" required aria-required="true" min="1" max="4">
        </div>
        <div class="submit">
            <input type="submit" value="Submit">
        </div>
    </fieldset>
</form>

1 Comment

Thank you for your contribution but this is not what I'm looking for. I would like to use javascript validation that I used above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.