Parts of the following code are from a quick form verification tutorial I found on YouTube. I'm trying to create an additional feature to generate a success message inside of the checkInputs() function if all the formControl class names = form-control success in the setSuccessFor(input) function. I created a variable allEl that converts the allElementsNode to an array, but I can't seem to iterate through that to pull the class names of the children. So [...allElementsNode][0] gives me access to the parent form element, so what I'm trying to do is iterate through all child divs in order to grab the class value to compare if it is equal to form-control success. If I try to iterate through allEl, I get undefined.
HTML
<form class="form" id="form">
<div class="form-control">
<label>Username</label>
<input type="text" placeholder="Angel" id="username">
<i class="fa fa-check-circle"></i>
<i class="fa fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label>Email</label>
<input type="email" placeholder="angel#gmail.com" id="email">
<i class="fa fa-check-circle"></i>
<i class="fa fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label>Password</label>
<input type="password" placeholder="password" id="password">
<i class="fa fa-check-circle"></i>
<i class="fa fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label>Password check</label>
<input type="password" placeholder="Password two" id="password2">
<i class="fa fa-check-circle"></i>
<i class="fa fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<button>Submit</button>
</form>
JavaScript
const form = document.querySelector('#form');
const username = document.querySelector('#username');
const email = document.querySelector('#email');
const password = document.querySelector('#password');
const password2 = document.querySelector('#password2');
let allElementsNode = document.querySelectorAll("#form");
const allElementsArray = Array.from(allElementsNode);
let formControl;
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
// get values from the inputs
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
if (usernameValue === '') {
// show error
setErrorFor(username, 'Username cannot be blank');
} else {
// show success
setSuccessFor(username);
}
if (emailValue === '') {
// show error
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Email is not valid')
} else {
// show success
setSuccessFor(email);
}
if (passwordValue === '') {
// show error
setErrorFor(password, 'Passwords cannot be blank');
} else {
// show success
setSuccessFor(password);
}
if (password2Value === '' || password2Value !== passwordValue) {
// show error
setErrorFor(password2, 'Passwords cannot be blank and must match!');
} else {
// show success
setSuccessFor(password2);
}
// Set success message. All formControl should have the success class set
// console.log(formControl.className)
const allEl = [...allElementsNode][0];
console.log(allEl);
const allCtrlEl = Array.from(allEl).forEach(item => item);
console.log(allCtrlEl);
}
function setErrorFor(input, message) {
formControl = input.parentElement; // .form-control
const small = formControl.querySelector('small');
// add error message inside small
small.innerText = message;
// add error class
formControl.className = 'form-control error';
}
function setSuccessFor(input) {
formControl = input.parentElement; // .form-control
formControl.className = 'form-control success';
}
function isEmail(email) {
const emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(email);
}
It looks like your allElementsNode is the parent form so you need to get childrenElements like so
const allEl = [...allElementsNode.children];
Related
Below is html code for login form
<h2 class="title">Sign in</h2>
<div class="input-field">
<i class="fas fa-user"></i>
<input type="email" id="email" placeholder="Email"/>
</div>
<div class="input-field">
<i class="fas fa-lock"></i>
<input type="password" id="password" placeholder="New Password" />
</div>
<input type="submit" value="Login" class="btn solid" onclick="login()" />
Below is .js file code for login function
function login () {
alert('Login Function')
// Get all our input fields
email = document.getElementById('email').value
password = document.getElementById('password').value
// Validate input fields
if (validate_email(email) == false || validate_password(password) == false) {
alert('Email or Password is Outta Line!!')
return
// Don't continue running the code
}
auth.signInWithEmailAndPassword(email, password)
.then(function() {
// Declare user variable
var user = auth.currentUser
// Add this user to Firebase Database
var database_ref = database.ref()
// Create User data
var user_data = {
last_login : Date.now()
}
// Push to Firebase Database
database_ref.child('users/' + user.uid).update(user_data)
// DOne
alert('User Logged In!!')
})
.catch(function(error) {
// Firebase will use this to alert of its errors
var error_code = error.code
var error_message = error.message
alert(error_message)
})
}
everything is working fine but my web app is not connected to a database of firebase
Note I've already required library or dependencies whatever you want to call in both HTML and js files.
i have a simple form where i am doing some validations in javascript, the submit button is prevented by default to check if all validations are done the form is like below:
const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
// trim to remove the whitespaces
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
if (usernameValue === '') {
setErrorFor(username, 'Full name cannot be blank');
} else {
setSuccessFor(username);
}
if (emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if (passwordValue === '') {
setErrorFor(password, 'Roll number cannot be blank');
} else if (passwordValue.length < 10) {
setErrorFor(password, 'Roll number must be 10 digits');
} else {
setSuccessFor(password);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
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);
}
<form id="form" class="form" method="post" action="">
<div class="form-control">
<label for="username">Full Name</label>
<input type="text" placeholder="Full Name" id="username" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Email</label>
<input type="email" placeholder="Email" id="email" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Roll Number</label>
<input type="text" maxlength="10" placeholder="Roll Number" id="password" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<button type="submit">Submit</button>
</form>
the validations are working fine, the issue if the form is not getting submitted if all validations are successful, can anyone please tell me how to accomplish this, thanks in advance
Not getting submitted becouse for e.preventDefault();. So e.preventDefault(); exicute when form is not valid otherwise not needed.
const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
form.addEventListener('submit', e => {
if(!checkInputs())
e.preventDefault();
});
function checkInputs() {
// trim to remove the whitespaces
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
let error =true;
if (usernameValue === '') {
setErrorFor(username, 'Full name cannot be blank');
error =false;
} else {
setSuccessFor(username);
}
if (emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
error =false;
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
error =false;
} else {
setSuccessFor(email);
}
if (passwordValue === '') {
setErrorFor(password, 'Roll number cannot be blank');
error =false;
} else if (passwordValue.length < 10) {
setErrorFor(password, 'Roll number must be 10 digits');
error =false;
} else {
setSuccessFor(password);
}
return error;
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
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);
}
<form id="form" class="form" method="post" action="">
<div class="form-control">
<label for="username">Full Name</label>
<input type="text" placeholder="Full Name" id="username" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Email</label>
<input type="email" placeholder="Email" id="email" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Roll Number</label>
<input type="text" maxlength="10" placeholder="Roll Number" id="password" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<button type="submit">Submit</button>
</form>
I am making a function in JS that prevents you from submitting if there is something wrong.
When I click the submit button it does not check if the code is valid, which really bugs me. My expected outcome is to redirect to another page if it is valid, which doesn't happen! Please help!
const formm = document.querySelector('#CreateAccount')
const school = document.querySelector('#skool');
const username = document.querySelector('#username');
const email = document.querySelector('#email');
const pwd = document.querySelector('#password');
const conf = document.querySelector('#confpassword');
formm.addEventListener("submit", (event) => {
if (isFormValid() == true) {
window.location.assign("start.html");
console.log(2);
} else {
event.preventDefault();
console.log(30);
}
validateForm();
console.log(30);
});
function isFormValid() {
const inputscontainers = document.querySelectorAll('.inputs')
let result = true;
inputscontainers.forEach((container) => {
if (container.classList.contains("error")) {
return false;
}
})
}
function validateForm() {
if (username.value.trim() == '') {
setError(username, 'Name cannot be empty');
} else if (username.value.trim() < 5) {
setError(username, 'Idrc');
console.log(3);
} else {
setSuccess(username);
}
if (email.value.trim() == '') {
setError(email, 'You forgot to fill in your email.');
} else if (isEmailValid(email.value)) {
setSuccess(email);
} else {
setError(email, "Provide a valid email");
}
if (pwd.value.trim() == '') {
setError(pwd, "Password can't be empty");
} else if (pwd.value.trim().length < 6 || pwd.value.trim().length > 20) {
setError(pwd, 'Length must be minimum 6 characters and max 20.');
} else {
setSuccess(pwd);
}
if (conf.value.trim() == '') {
setError(conf, 'This is an empty password');
} else if (conf.value !== pwd.value) {
setError(conf, 'Passwords dont match');
} else {
setSuccess(conf);
}
}
function setError(elementr, errorMessage) {
const parents = elementr.parentElement;
parents.classList.add("error");
parents.classList.remove("success");
const paragraph = parents.querySelector('p').textContent = errorMessage;
}
function setSuccess(elementr) {
const parents = elementr.parentElement;
parents.classList.add("success");
parents.classList.remove("error");
}
function isEmailValid(email) {
const reg = /^(([^<>()[\]\.,;:\s#\"]+(\.[^<>()[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
return reg.test(email);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="CreateAccount" action="start.html" method="GET">
<div class="main">
<div class="Title">
<h1>Enter your details.</h1>
</div>
<div class="inputs">
<label for="skool">SchoolName:</label>
<input type="text" id="skool" placeholder="Put the school name" name="skool"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<div class="inputs">
<label for="username">Username:</label>
<input type="text" id="username" placeholder="Username" name="username">
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p id="p">Error Message</p>
</div>
<div class="inputs">
<label for="password">Password</label>
<input type="password" id="password" placeholder=" Password" name="password"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p id="p">Error Message</p>
</div>
<div class="inputs">
<label for="confpassword">Confirm Password</label>
<input type="password" id="confpassword" placeholder=" Confirm Password" name="confpassword"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<div class="inputs">
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Email" name="email"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<button class="submitbtn" type="submit">Submit</button>
</div>
</div>
Other than the inversion on validation / isValidForm, your isValidForm function doesn't return a result, so it can't be compared on a if statement
Here's how to fix it
formm.addEventListener("submit", (event) => {
validateForm();
if (isFormValid() == true) {
window.location.assign("start.html");
} else {
event.preventDefault();
}
});
function isFormValid() {
const inputscontainers = document.querySelectorAll('.inputs')
let result = true;
inputscontainers.forEach((container) => {
if (container.classList.contains("error")) {
return false;
}
})
return result;
}
I have made sure the Javascript is linked to the HTML I have also tried many Javascript online validation websites but none seem to have a solution to what I'm experiencing.
If the username value is empty the code is meant to show an error message and turn the username input border red hence the class changes but it seems that form continues to submit without showing any error messages.
const form = document.getElementById('form');
const username = document.getElementById('Username');
const password = document.getElementById('signup-password');
const confirm_password = document.getElementById('confirm_password');
const email = document.getElementById('email');
if (form) {
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
})
};
function checkInputs() {
const usernameValue = username.value.trim();
const passwordValue = password.value.trim();
const confirm_passwordValue = confirm_password.value.trim();
const emailValue = email.value.trim();
if (usernameValue === ' ' || usernameValue == null) {
setErrorFor(username, 'Username required');
} else {
setSuccessFor(username);
}
}
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 success'
}
This is also the relevant HTML
<body>
<div class="Container">
<div class="Header"><h2>Create Account</h2></div>
<form class="form" id="form">
<div class="form-control">
<label class="Username" for="username">User Name</label>
<input type="text" id="Username" placeholder = "yeeno3">
<small>Error message</small>
</div>
<div class="form-control">
<label class="email" for="email">Email Address</label>
<input type="email" id="email" placeholder = "zoroisstrongerthanluffy#gmail.com">
<small>Error message</small>
</div>
<div class="form-control">
<label class="password" for="signup-password">Password</label>
<input type="password" id="signup-password" placeholder = "Password">
<small>Error message</small>
</div>
<div class="form-control">
<label class="confirm_password" for="password">Confirm Password</label>
<input type="password" id="confirm_password" placeholder = "Confirm Password">
<small>Error message</small>
</div>
<input type="submit" style="display: none"/>
<button>Submit</button>
<input type="submit" id="real-file" hidden="hidden" />
</form>
</div>
I suggest changing usernameValue === ' ' to usernameValue === ''. You have trimmed your usernameValue, so it will never be equal to a single space, i.e. ' '
The problem is here:
if (usernameValue === ' ' || usernameValue == null) { //compare this
if (usernameValue === '' || usernameValue == null) { // with this
You need to remove that space between quotes.
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();
});