form not being submitted even after full validation - javascript

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.

Related

Form not sending data via _POST

It's meant to be a basic web form but I am having issues with it. I have spent hours working on it but can't seem to find the problem.
I am getting the error message Cannot destructure property 'email' of 'req.body' as it is undefined. The full source code can be found here: https://github.com/SophalLee/project_06_sophal_lee. Here are snippets of my code:
index.js
app.post('/login', (req, res) => {
const { email, password } = req.body;
console.log(email);
})
login-form.js
import { checkName, numbersAndSpaceCheck, emailCheck } from '/js/validation.js';
const loginForm = document.getElementById('login');
const email = document.getElementById('email');
const password = document.getElementById('password');
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
if(checkInputs()) {
loginForm.submit();
}
});
/* Validate input from form */
function checkInputs() {
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
let emailSuccess = false;
let passwordSuccess = false;
if(emailValue === '') {
setErrorFor(email, "Email cannot be blank");
emailSuccess = false;
}
else if(!emailCheck(emailValue)) {
setErrorFor(email, "Invalid email");
emailSuccess = false;
}
else {
setSuccessFor(email);
emailSuccess = true;
}
if(passwordValue === '') {
setErrorFor(password, "Password cannot be blank");
passwordSuccess = false;
}
else {
setSuccessFor(password);
passwordSuccess = true;
}
return (emailSuccess & passwordSuccess);
}
/* Display error message and error icon */
export function setErrorFor(input, message) {
const formControl = input.parentElement;
const error = formControl.querySelector('.error-message');
error.className = 'error-message error';
error.innerText = message;
formControl.className = 'form-control error';
}
/* Display success icon and remove any error message */
export function setSuccessFor(input) {
const formControl = input.parentElement;
const error = formControl.querySelector('.error-message');
error.className = 'error-message';
formControl.className = 'form-control success';
}
login.ejs
<!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">
<script src="https://kit.fontawesome.com/cf53bba659.js" crossorigin="anonymous"></script>
<link href="/css/forms.css" rel="stylesheet" type="text/css"/>
<script type="module" src="/js/login-form.js" defer></script>
<title>Locations - Login</title>
</head>
<body>
<div class="container">
<div class="header">
<h1>Login</h1>
</div>
<form class="form" id="login" action="/login" method="POST" novalidate>
<div class="form-control">
<label for="email">Email</label>
<input name="email" id="email" type="text" required>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<div class="error-message"> </div>
</div>
<div class="form-control">
<label for="password">Password</label>
<input name="password" id="password" type="password" required>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<div class="error-message"> </div>
</div>
<button>Submit</button>
</div>
</form>
</div>
</body>
</html>
I just needed the following line in index.js file:
app.use(express.urlencoded({ extended: true }));

Uncaught ReferenceError function not defined for password and repassword

I have this error message below despite setting the javascript in the html. The code below is my html code for registration but none of the javascript function or event listener are working. I am still learning about javascript and html so please advice on what I did wrong.
Error message
Uncaught ReferenceError: matchTest is not defined at HTMLInputElement.onkeyup
Register page
<div class="form">
<form id="register-form" action="#">
<ul class="form-container">
<li>
<h2>Create Account</h2>
</li>
<li>
<label for="name">Name</label>
<input type="name"
name="name"
id="name"
required />
</li>
<li>
<label for="email" class="emailBox">Email</label>
<input type="email"
name="email"
id="email"
required
/>
<span class="emailText"></span>
</li>
<li>
<label for="password" class="passBox">Password</label>
<input type="password"
id="password"
name="password"
class="password"
required
/>
<span class="passText"></span>
</li>
<li>
<label for="re-password">Re-Enter Password</label>
<input type="password"
id="re-password"
name="re-password"
class="re-password"
onkeyup="matchTest()"
required
/>
</li>
<li>
<button type="submit" class="primary">
Register
</button>
</li>
<li>
<div>Already have an account? Sign-In
</div>
</li>
</ul>
</form>
<script type="text/javascript">
window.onload = function() {
let email = document.getElementById("email")
let password = document.getElementById("password")
email.addEventListener('input',()=>{
let emailBox = document.querySelector('.emailBox')
let emailText = document.querySelector('.emailText')
const emailPattern = /[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/
if(email.value.match(emailPattern)){
emailBox.classList.add('valid')
emailBox.classList.remove('invalid')
emailText.innerHTML = "Your Email Address in Valid"
}else{
emailBox.classList.add('invalid')
emailBox.classList.remove('valid')
emailText.innerHTML = "Must be a valid email address."
}
})
password.addEventListener('input',()=>{
let passBox = document.querySelector('.passBox');
let passText = document.querySelector('.passText');
const passPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;
if(password.value.match(passPattern)){
passBox.classList.add('valid');
passBox.classList.remove('invalid');
passText.innerHTML = "Your Password in Valid";
}else{
passBox.classList.add('invalid');
passBox.classList.remove('valid');
passText.innerHTML = "Your password must be at least 8 characters as well as contain at least one uppercase, one lowercase, and one number.";
}
})
function matchTest(){
let password = document.querySelector('password').value
let confirmPassword = document.querySelector('re-password').value
if(password != confirmPassword)
alert("Password don't match. Please try again.")
return false
}
else if(password == confirmPassword){
alert("Password match")
}
}
}
</script>
</div>
You need to change following things:
It is recommended to define addEventListener in JS not inline
repeatPassword.addEventListener("keyup", (e) => { matchTest(); });
Since you've defined the variable password, so it would be consistent to add repeatPassword also and get its value as password.value and reapatPassword.value in matchTest.
It is recommended to use === instead of ==.
I've used console.log in place of alert. Since you are checking for password equality then it's annoying to get alert after every key press.
window.onload = function() {
let email = document.getElementById("email");
let password = document.getElementById("password");
let repeatPassword = document.getElementById("re-password");
email.addEventListener("input", () => {
let emailBox = document.querySelector(".emailBox");
let emailText = document.querySelector(".emailText");
const emailPattern = /[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/;
if (email.value.match(emailPattern)) {
emailBox.classList.add("valid");
emailBox.classList.remove("invalid");
emailText.innerHTML = "Your Email Address in Valid";
} else {
emailBox.classList.add("invalid");
emailBox.classList.remove("valid");
emailText.innerHTML = "Must be a valid email address.";
}
});
password.addEventListener("input", () => {
let passBox = document.querySelector(".passBox");
let passText = document.querySelector(".passText");
const passPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;
if (password.value.match(passPattern)) {
passBox.classList.add("valid");
passBox.classList.remove("invalid");
passText.innerHTML = "Your Password in Valid";
} else {
passBox.classList.add("invalid");
passBox.classList.remove("valid");
passText.innerHTML =
"Your password must be at least 8 characters as well as contain at least one uppercase, one lowercase, and one number.";
}
});
function matchTest() {
let pass = password.value;
let confirmPass = repeatPassword.value;
if (pass !== confirmPass) {
console.log("Password don't match. Please try again.");
return false;
} else {
console.log("Password match");
}
}
repeatPassword.addEventListener("keyup", (e) => {
matchTest();
});
};
<div class="form">
<form id="register-form" action="#">
<ul class="form-container">
<li>
<h2>Create Account</h2>
</li>
<li>
<label for="name">Name</label>
<input type="name" name="name" id="name" required />
</li>
<li>
<label for="email" class="emailBox">Email</label>
<input type="email" name="email" id="email" required />
<span class="emailText"></span>
</li>
<li>
<label for="password" class="passBox">Password</label>
<input type="password" id="password" name="password" class="password" required />
<span class="passText"></span>
</li>
<li>
<label for="re-password">Re-Enter Password</label>
<input type="password" id="re-password" name="re-password" class="re-password" required />
</li>
<li>
<button type="submit" class="primary">
Register
</button>
</li>
<li>
<div>Already have an account? Sign-In
</div>
</li>
</ul>
</form>
</div>

setCustomValidity error but the form is submitted

I'm using setCustomValidity function to check if the new password and the repeat password are equals but , I debugged the code and the comparisson its correct but the error message its not shown and the form post request its done
<form action="/register" method="post" onsubmit="check_new_password()">
<div class="form-group">
and the javascript
function check_new_password(){
var new_pass = $('#new-password').val();
var repeated_pass = $('#repeat-password').val();
if(new_pass != repeated_pass){
$('#repeat-password')[0].setCustomValidity('Password are not equals');
}else{
$('#repeat-password')[0].setCustomValidity('');
}
You need to add the return statement in the onsubmit attribute, like this:
onsubmit="return check_new_password();"
So, the check_new_password() function needs to return a boolean according the validation.
Don't forget call the .reportValidity(); method because you're using HTMLObjectElement.setCustomValidity() method.
Additionally, you should add oninput="setCustomValidity('');" on the inputs fields to force to update its state.
See in this example:
function check_new_password() {
var new_pass = $('#new-password').val();
var repeated_pass = $('#repeat-password').val();
if (new_pass != repeated_pass) {
$('#repeat-password')[0].setCustomValidity('Password are not equals.');
$('#repeat-password')[0].reportValidity();
return false;
} else {
$('#repeat-password')[0].setCustomValidity('');
return true;
}
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<form action="/register" method="post" onsubmit="return check_new_password();">
<div class="form-group">
<label for="new-password">Password:</label>
<input id="new-password" class="form-control" type="password" oninput="setCustomValidity('');" />
</div>
<div class="form-group">
<label for="repeat-password">Repeat Password:</label>
<input id="repeat-password" class="form-control" type="password" oninput="setCustomValidity('');" />
</div>
<div>
<button class="btn btn-xs btn-primary" type="submit">Send</button>
</div>
</form>
</div>

Form Submit Not Working - html, css and javascript, can't get form to hide either

I'm trying to make a form and two things are not working. The form doesn't submit and I can't get it to hide either. I'm trying to make it so if the user clicks on the binocular icon it displays the form and it's hidden until the user does so. I'm a UX Designer trying to up my front-end skills.
HTML:
<body>
<a href onclick="document.getElementById('hide').style.display='block'">
<img src="iconmonstr-binoculars-8.png" width="40" height="30" alt=""/>
</a><br>
<p id="demo" style="display:none">
<div class="container">
<h2>Have a Product Suggestion?</h2>
<form class="form" id="form">
<div class="form-control">
<label for="fName">Full Name</label><br>
<input type="text" id="Fname" placeholder="Lisa Simpson" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i><br>
<small>Error Message</small><br>
</div>
<div class="form-control">
<label for="email">Email Address</label><br>
<input type="email" placeholder="iheartthesax#gmail.com" id="email" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i><br>
<small>Error Message</small><br>
</div>
<div class="form-control">
<label for="productDes">Product Description</label><br>
<textarea name="message" rows="4" cols="35" id="productDes">Describe the product you are looking for, please be as detailed as possible.
</textarea>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i><br>
<small>Error Message</small><br>
</div>
<input type="submit" value="Submit" /><br>
</form>
</div></p>
Javascript:
const form = document.getElementById('form');
const fname = document.getElementById('fname');
const email = document.getElementById('email');
const productDes = document.getElementById('productDes');
form.addEventListener('Submit', (e) => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
//get the values from the inputs
const fnameValue = fname.value.trim();
const emailValue = email.value.trim();
const productDesValue = productDes.value.trim();
if(fnameValue === '' ) {
setErrorFor(fname, 'Oh no! Please add your name.');
} else {
setSuccessFor(fname);
}
if(emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if(productDesValue === '' ) {
setErrorFor(productDes, 'Oh no! Please add details for the product.');
} else {
setSuccessFor(productDes);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.queryselector('small');
small.innerText = message;
formControl.className = 'form-control error';
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control sucess';
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
document.getElementById("hide").style.display = "block";
'''
So for the hiding with document.getElementById("hide").style.display = "block" and document.getElementById('hide').style.display='block' you are trying to change the display value of something with the id hide. I see no such element in your HTML.
I think what you actually want to do is make the Element wit the ID demo visible again right? So for the hiding I guess using document.getElementById("demo").style.display = "block" would fix your problem.
And for the submitting, I am not sure but the events might be case sensitive, have you tried registering to the submit event instead of Submit?
Replace submit event handler with this code. It will submit the form.
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});

Bootstrap login with javascript

I'm new to Javascript and I need to validate a log-in form with Bootstrap, the thing is not validating the password in the script.
https://jsfiddle.net/98uqsvu2/
<script type="text/javascript">
function check_info()
{
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if(user == "test#gmail.com")
{
if(pass == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
git: https://gist.github.com/Adaryn/6c38cfafd5e95d8a0bba508a33cebec7
#Adaryn
Since I cannot comment, I posted it as an answer.
I made the following changes to the fiddle and I was able to execute the code.
Removed the link href's from your HTML.
Added the closing body tag.
Moved the script from the javascript code section and pasted it just above the closing body tag.
Here is the updated fiddle.
<div class="container">
<form class="form-signin" form role="form" action="hola.html" name="formlogin" method="post" class="login-form" onsubmit="check_info()">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required="">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<script type="text/javascript">
function check_info()
{
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if(user == "test#gmail.com")
{
if(pass == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
try this code. also added jsfiddle
document.getElementById("submit-form").addEventListener("click", check_info);
function check_info() {
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if (user == "test#gmail.com" && pass == "123") {
alert("email and password is valid!!!");
return true;
} else {
alert("email and password is NOT valid!!!");
return false;
}
}
https://jsfiddle.net/damaxrss/

Categories