简体   繁体   中英

form not being submitted even after full validation

Ideal Case:

  • if form valid send data to the servlet.
  • if not show the respective errors

What actually is happening: when i submit a form with wrong credentials the form gets stuck and the data does not go to the servlet which is what we want but when I enter the right credentials even then the form is not being submitted to the servlet. Here is my JavaScript code:

const form = document.getElementById('register-form');
const fname = document.getElementById('fname');
const lname = document.getElementById('lname');
const email = document.getElementById('email');
const password = document.getElementById('password');

const sendData = (fnameVal, sRate, count) => {
    if (sRate === count) {
        swal("Congratulations " + fnameVal + " !", "Account Created Successfully", "success");
        form.submit();
    }
}

const successMsg = (fnameVal) => {
    let formG = document.getElementsByClassName('form-group');
    var count = formG.length - 1;
    for (var i = 0; i < formG.length; i++) {
        if (formG[i].className === "form-group success") {
            var sRate = 0 + i;
            sendData(fnameVal, sRate, count);
        } else {
            return false;
        }
    }
}

const isEmail = (emailVal) => {
    var re = /^\S+@\S+\.\S+$/;
    if (!re.test(emailVal)) return false;
    var atSymbol = emailVal.indexOf("@");
    if (atSymbol < 1) return false;
    var dot = emailVal.indexOf('.');
    if (dot === emailVal.length - 1) return false;
    return true;
}

const isPassword = (passwordVal) => {
    var re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
    if (!re.test(passwordVal)) {
        return false;
    } 
    return true;
}

const validate = () => {
    const fnameVal = fname.value.trim();
    const lnameVal = lname.value.trim();
    const emailVal = email.value.trim();
    const passwordVal = password.value.trim();
        
    // validate first-name
    if (fnameVal.length <= 2) {
        setErrorMsg(fname, 'first-name requires min 3 char');
    } else {
        setSuccessMsg(fname);
    }

    // check last-name
    if (lnameVal.length <= 2) {
        setErrorMsg(lname, 'last-name requires min 3 char');
    } else {
        setSuccessMsg(lname);
    }

    // check email
    if (!isEmail(emailVal)) {
        setErrorMsg(email, 'not valide email');
    } else {
        setSuccessMsg(email);
    }

    // check password
    if (!isPassword(passwordVal)) {
        setErrorMsg(password, "min 8 char, at least 1 uppercase and lowercase letter, one number and special character");
    } else {
        setSuccessMsg(password);
    }
    successMsg(fnameVal);
}

function setErrorMsg(input, errormsgs) {
    const formGroup = input.parentElement;
    const small = formGroup.querySelector('small');
    formGroup.className = "form-group error";
    small.innerText = errormsgs;
}

function setSuccessMsg(input) {
    const formGroup = input.parentElement;
    formGroup.className = "form-group success";
}

var s = document.getElementById("status").value;
if (s == "success") {
    swal("Congratulations", "Account Created Successfully", "success");
} 

Here is my HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QuizzBuzz Sign-Up Portal</title>

    <link rel="stylesheet" href="./css/registration-style.css">

    <!--font-->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
<input type="hidden" name="hiddenalert" id = "status" value = "<%= request.getAttribute("hiddenalert") %>">
    <div class="main">
        <section class="signup">
            <div class="container">
                <div class="signup-content">
                    <div class="signup-image">
                        <figure>
                            <img src="./images/signup-image.jpg" alt="singup-image">
                        </figure>
                    </div>
                    <div class="signup-form">
                        <h2 class="title">Create an Account</h2>
                        <form method="post" action="Register" class="register-form" id="register-form">
                            <div class="form-group">
                                <select id="userType" class="userType" name="userType" required="required">
                                    <option value="student">Student</option>
                                    <option value="teacher">Teacher</option>
                                    <option value="admin">Admin</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <input type="text" name="firstname" id="fname" placeholder="Enter your first-name" autocomplete="off" required="required">
                                <i class="fa-solid fa-circle-check"></i>
                                <i class="fa-solid fa-exclamation-circle"></i>
                                <small>Error!</small>
                            </div>
                            <div class="form-group">
                                <input type="text" name="lastname" id="lname" placeholder="Enter your last-name" autocomplete="off" required="required">
                                <i class="fa-solid fa-circle-check"></i>
                                <i class="fa-solid fa-exclamation-circle"></i>
                                <small>Error!</small>
                            </div>
                            <div class="form-group">
                                <input type="email" name="email" id="email" placeholder="Enter your Email ID" autocomplete="off" required="required">
                                <i class="fa-solid fa-circle-check"></i>
                                <i class="fa-solid fa-exclamation-circle"></i>
                                <small>Error!</small>
                            </div>
                            <div class="form-group">
                                <input type="password" name="password" id="password" placeholder="Enter your password" autocomplete="off" required="required">
                                <i class="fa-solid fa-circle-check"></i>
                                <i class="fa-solid fa-exclamation-circle"></i>
                                <small>Error!</small>
                            </div>
                            <input type="submit" value="Submit" onclick = "event.preventDefault(); validate()"  class="button">
                        </form>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="./js/member-registration.js"></script>
</body>
</html>

I think it has something to do with the event.preventDefault() function but i dont know exactly how to get around the problem and solve it.And the sweet alerts also do not work

I highly recommend you to validate users and passwords formats also in servlets(or server side).

This because people could just erase or stop all javascript validation and directly send their data.

Validating in client side is not wrong but is not secure at all.

Now, answering your request, if the credentials are in a correct format you are just submitting the form tag like this.

<form method="post" action="Register" class="register-form" id="register-form">

The "action" attribute work is redirecting the form content to the url you write in it.

So action="Register" is not correct(If you were reaching a servlet, it have to be a valid path, like: '/Register').

In it's place, you have to write a relative path that is current being listened by a servlet or a jsp, like this:

action="register.jsp" or action="/register"

This way, when you submit your form, it is gonna redirect you and your form content to the path you wrote.

Another way is send data trough ajax(You can research it), the form data is sent without reloading and your javascript recives a response from the server.

Let me know if i helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM