Please guys i created a form validation program using html, css and javascript and i want the form to validate when they user input changes though i am not getting error but the form is not validating, can any one resolve my program and detect my mistakes
const loader = document.querySelector('.loader');
// selecting inputs
const submitBtn = document.querySelector('.submit-btn');
const names = document.querySelector('#name');
const email = document.querySelector('#email');
const password = document.querySelector('#password');
const num = document.querySelector('#number');
const tac = document.querySelector('#terms-and-con');
const notification = document.querySelector('#notification');
/// showalert function
const showAlert = (msg) => {
let alertMsg = document.querySelector('.alert-msg');
let alertBox = document.querySelector('.alert-box');
alertMsg.innerHMTL = msg;
alertBox.classList.add('show');
setTimeout(() => {
alertBox.classList.remove('show');
}, 3000)
}
/// send data function
const sendData = (path, data) => {
fetch(path, {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(data),
}).then((res) => res.json()).then(response => {
processData(response);
})
}
/// submit button functionality
submitBtn.addEventListener('click', () => {
if (name.value.length < 3) {
// showAlert('name must be 3 letters long');(
alert('bad input')
} else if (!email.value.length) {
showAlert('enter your email');
} else if (password.value.length < 9) {
showAlert('password should be eight letters long');
}
})
this is the html program
<div>
<input type="text" autocomplete="off" id="name" placeholder="name">
<input type="email" autocomplete="off" id="email" placeholder="email">
<input type="password" autocomplete="off" id="password" placeholder="password">
</label>
<br>
<input type="checkbox" class="checkbox" id="notification">
<label for="notification">receive upcoming offers and events mails</label>
<button class="submit-btn">create account</button>
</div>
already have an account?. Login in here
</div>
<div class="alert-box ">
<img src="img/error.png" alt="" class="alert-image">
<p class="error-message alert-msg">
There is an error
</p>
</div>
i think here
if(name.value.length < 3){ // name.value.length should be names.value.length as its
// here const names = document.querySelector('#name');
// just a typo nothing to worry about your code should
// work
and a suggestion check all three fields seprately regardless of if name is fine then check email and if email is fine then check password, btw your code is just fine it should work
Related
I am creating a JavaScript form with validation. It is functional on first data entry into the form, however, once you correctly receive a data validation error for an incorrect input, then the functionality stops, the submit button stays locked and I do not know how to undo it.
I have used the ".preventDefault()" to stop inputs going through, but I do not know how to undo this method after a data validation error has already been given.
client-side-form-validation.js
const signupForm = document.getElementById('signup-form');
const email = document.getElementById('email');
const password = document.getElementById('password');
const emailError = document.getElementById('email-error');
const passwordError = document.getElementById('password-error');
// Email field client side form validation
signupForm.addEventListener('submit', (e) => {
let emailMessages = []
if (email.value === '' || email.value == null){
emailMessages.push('Email is required')
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email.value)){
emailMessages.push('Email is invalid')
}
if(emailMessages.length > 0){
e.preventDefault()
emailError.innerHTML = emailMessages.join('<br>')
}
});
// Password field client side form validation
signupForm.addEventListener('submit', (e) => {
let passwordMessages = []
if (password.value === '' || password.value == null){
passwordMessages.push('Password is required')
}
if(passwordMessages.length > 0){
e.preventDefault()
passwordError.innerHTML = passwordMessages.join('<br>')
}
});
signup.ejs
<form id="signup-form" action='/signup' method="post">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<div class="signup-error" id="email-error"></div>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<div class="signup-error" id="password-error"></div>
<input type="submit" value="Submit">
</form>
Thanks for your time :)
I played around with the code for a little and came up with my own answer.
My answer involved attaching a else statement to the if statements, deleting the array and then posting the deleted array to the error message in the form.
if(emailMessages.length > 0){
e.preventDefault();
emailError.innerHTML = emailMessages.join('<br>');
}else{
delete emailMessages;
emailError.innerHTML = emailMessages.join('<br>');
}
Then do the same for the password validation.
It seems to work here.
Update: made it more friendly by checking the error on change as well as on submit.
const signupForm = document.getElementById('signup-form');
const email = document.getElementById('email');
const password = document.getElementById('password');
const emailError = document.getElementById('email-error');
const passwordError = document.getElementById('password-error');
signupForm.addEventListener('submit', (e) => {
if (!validate_email()) {
e.preventDefault()
}
if (!validate_password()) {
e.preventDefault()
}
// continue to submit
});
email.addEventListener('change', validate_email);
password.addEventListener('change', validate_password);
function validate_email() {
let messages = []
if (email.value === '' || email.value == null) {
messages.push('Email is required')
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email.value)) {
messages.push('Email is invalid')
}
var valid = !messages.length;
emailError.innerHTML = valid ? "" : messages.join('<br>')
return valid;
}
function validate_password() {
let messages = []
if (password.value === '' || password.value == null) {
messages.push('Password is required')
}
var valid = !messages.length;
passwordError.innerHTML = valid ? "" : messages.join('<br>')
return valid;
}
.signup-error {
color: red;
}
.form-group {
margin-bottom: 10px;
}
<form id="signup-form" action='/signup' method="post">
<div class="form-group">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<div class="signup-error" id="email-error"></div>
</div>
<div class="form-group">
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<div class="signup-error" id="password-error"></div>
</div>
<input type="submit" value="Submit">
</form>
const params = new URLSearchParams(window.location.search);
$(document).ready(_ => {
if (params.get("url") != null) {
$("input")[0].value = params.get("url");
}
if (params.get("img") != null) {
$("input")[1].value = params.get("img");
}
});
let url;
let img;
let submit = _ => {
url = $("input")[0].value;
img = $("input")[1].value;
if (!url.length) {
return alert('Please enter URL');
}
}
let send = _ => {
$.ajax({
type: "POST",
url: url,
async: true,
data: {
file: (img)
},
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="box">
<p title="Webhook url to send spam message">Webhook URL</p><input required name="inp1" placeholder="https://discord.com/api/webhooks/........." type="url" autocomplete></input>
</div>
<div class="box">
<p title="Message you want to spam it">Image</p><input required name="inp2" placeholder="Image Link" type="file"></input>
</div>
<a onclick="submit()"><button id="button" >Send</button></a>
I want the attachment to be sent through the API in discord chat. I tried doing it like this but it doesn't work. The file:() I think might be the issue but also the input type I don't know
Without jQuery you might try something like this using the fetch api in conjunction with the FormData interface and the FileList
const d=document;
const q=(e,n=d)=>n.querySelector(e);
d.addEventListener('DOMContentLoaded', ()=>{
q('button#button').addEventListener('click', e=>{
e.preventDefault();
let url = q('input[name="inp1"]').value;
let files = q('input[name="inp2"]').files;
if (!url.length) return alert('Please enter URL');
let fd = new FormData();
fd.set('url', url);
fd.set('img', files.item(0));
fetch( url, { method:'post', body:fd } )
.then(r=>r.text())
.then(text=>{
alert(text)
})
})
});
<div class="box">
<p title="Webhook url to send spam message">Webhook URL</p>
<input required name="inp1" placeholder="https://discord.com/api/webhooks/........." type="url" autocomplete />
</div>
<div class="box">
<p title="Message you want to spam it">Image</p>
<input required name="inp2" placeholder="Image Link" type="file" />
</div>
<button id="button">Send</button>
The jQuery version is quite probably not quite correct as the snippet yields an error with the $.post method and being unfamiliar with jQuery I cannot see the mistake
const params = new URLSearchParams( window.location.search );
$(document).ready(() => {
let url;
let img;
let fd=new FormData();
if( params.get("url") != null ) {
$("input[name='inp1']")[0].value = params.get("url");
};
$('#button').click(e=>{
url = $("input[name='inp1']")[0].value;
img = $("input[name='inp2']")[0];
if( !url.length ) {
return alert('Please enter URL');
}
fd.set('url',url);
fd.set('img',img.files.item(0));
$.ajax({
type:"POST",
url:url,
data:fd,
success:r=>{console.log(r)},
error:e=>{console.warn(e)}
});
});
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="box">
<p title="Webhook url to send spam message">Webhook URL</p>
<input required name="inp1" placeholder="https://discord.com/api/webhooks/........." type="url" autocomplete />
</div>
<div class="box">
<p title="Message you want to spam it">Image</p>
<input required name="inp2" placeholder="Image Link" type="file" />
</div>
<button id="button">Send</button>
Worth noting perhaps is that you cannot set the value of a file input element programmatically - only the user can set this value by browsing for and selecting a file.
I made client side form validation for my signup form and there everything works fine. However on my login form the validation doesn't work like it is supposed to. On the login form it only shows the error status messages and only if I enter a correct value will it show the success message and green border. Another problem I have is that the text of the error message is not red or green only the border of the input changes color .The Javascript code is completely the same for the both of these it's only the html that is different.
HTML signup form
<form id="signup-form" class="form" method="POST" action="./includes/signup.inc.php">
<div class="mb-3 input-control">
<label for="full-name">Full name\User name</label><br>
<p>*You can only have on user name per e-mail account</p>
<input type="text" class="form-control" id="full-name" name="full-name"
placeholder="John Smith">
<small class="message" id="message-full-name"></small>
<br>
</div>
<div class="mb-3 input-control">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email"
placeholder="JohnSmith#gmail.com">
<small class="message" id="message-email"></small>
<br>
</div>
<div class="mb-3 input-control">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password"
placeholder="Password">
<small class="message" id="message-password"></small>
<br>
</div>
<div class="mb-3 input-control">
<label for="pwdRepeat">Password repeat</label>
<input type="password" class="form-control" id="pwdRepeat" name="pwdRepeat"
placeholder="Retype Password">
<small class="message" id="message-pwdRepeat"></small>
<br>
</div>
Forgot your password?
<div class="modal-footer">
<button type="reset" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" id="submit" class="btn btn-primary" name="submit">Register now</button>
</div>
<script src="./js/signup_error_handler.js"></script>
</form>
Javascript for the signup form
const form = document.getElementById('signup-form');
const name = document.getElementById('full-name');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password_repeat = document.getElementById('pwdRepeat');
form.addEventListener('submit', e => {
if (validateInputs()) {
e.currentTarget.submit();
} else {
e.preventDefault();
}
});
function validateInputs() {
//Get the value from inputs
const nameValue = name.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const passwordRepeatValue = password_repeat.value.trim();
let return_value = false;
//These variables are set with one when the value of the input field is correct
let name_check = 0;
let email_check = 0;
let password_check = 0;
let password_repeat_check = 0;
if (nameValue === '') {
//Show error and set error class
setError(name, 'Your name cannot be empty');
} else {
//Add success class
setSuccess(name);
name_check = 1;
}
if (emailValue === '') {
//Show error and set error class
setError(email, 'Email field cannot be empty');
} else if (!isEmail(emailValue)) {
setError(email, 'Email is not valid');
} else {
//Add success class
setSuccess(email);
email_check = 1;
}
if (passwordValue === '') {
//Show error and set error class
setError(password, 'Password field cannot be empty');
} else if (passwordValue.length <= 6) {
setError(password, 'Please enter a longer password');
} else {
//Add success class
setSuccess(password);
password_check = 1;
}
if (passwordRepeatValue === '') {
//Show error and set error class
setError(password_repeat, 'Password repeat field cannot be empty');
} else if (passwordValue !== passwordRepeatValue) {
setError(password_repeat, 'The passwords do not match');
}else if (passwordRepeatValue.length <= 6){
setError(password_repeat,"Repeated password needs to be longer")
} else {
//Add success class
setSuccess(password_repeat);
password_repeat_check = 1;
}
if (name_check === 1 && email_check === 1 && password_check === 1 && password_repeat_check === 1) {
return_value = true;
} else {
return_value = false;
}
return return_value;
}
function setError(element, message) {
element.className = "form-control error";
const small = document.getElementById("message-" + element.id);
small.classList.remove('success');
//Add error message and icon
small.innerHTML = message + ' <i class="fas fa-exclamation-circle">';
//Add error class
small.classList.add("error");
}
const setSuccess = (element) => {
element.className = "form-control success";
const small = document.getElementById("message-" + element.id);
small.classList.remove('error');
//Add success icon
small.innerHTML = '<i class="fas fa-check-circle">';
//Add success class
small.classList.add("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);
}
Html for the login form( the one that doesn't work like it's supposed to)
<form id="login-form" action="./includes/login.inc.php" method="POST">
<label for="login-email" class="call-form-label">
Email:
</label>
<input type="email" class="form-control" name="email" id="login-email" placeholder="Email">
<small class="message" id="message-login-email"></small>
<br>
<label for="login-password" class="call-form-label">
Password:
</label>
<input type="password" class="form-control" name="password" id="login-password" placeholder="Password">
<small class="message" id="message-login-password"></small>
<br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" name="login-submit" id="login-submit" class="btn btn-primary">Login</button>
<hr>
<p>Did not receive Your Verification Email?
Resend
</p>
</div>
</form>
Javascript for the login form
const login_form = document.getElementById('login-form');
const login_email = document.getElementById('login-email');
const login_password = document.getElementById('login-password');
login_form.addEventListener('submit', e => {
if (login_validateInputs()) {
e.currentTarget.submit();
} else {
e.preventDefault();
}
});
function login_validateInputs() {
//Get the value from inputs
const login_email_value = login_email.value.trim();
const login_password_value = login_email.value.trim();
//These variables are set with one when the value of the input field is correct
let login_email_check = 0;
let login_password_check = 0;
if (login_email_value === '') {
//Show error and set error class
login_setError(login_email, "Email field cannot be empty");
} else if (!login_isEmail(login_email_value)) {
login_setError(login_email, "Email is not valid");
} else {
//Add success class
login_setSuccess(login_email);
login_email_check = 1;
}
if (login_password_value === '') {
//Show error and set error class
login_setError(login_password, 'Password field cannot be empty');
} else if (login_password_value.length <= 6) {
login_setError(login_password, 'Please enter a longer password');
} else {
//Add success class
login_setSuccess(password);
login_password_check = 1;
}
if (login_password_check === 1 && login_email_check === 1) {
return_value = true;
} else {
return_value = false;
}
return return_value;
}
function login_setError(element, message) {
element.className = "form-control error";
const small = document.getElementById("message-" + element.id);
small.classList.remove('success');
//Add error message and icon
small.innerHTML = message + ' <i class="fas fa-exclamation-circle" >';
//Add error class
small.classList.add("error");
}
const login_setSuccess = (element) => {
element.className = "form-control success";
const small = document.getElementById("message-" + element.id);
small.classList.remove('error');
//Add success icon
small.innerHTML = '<i class="fas fa-check-circle">';
//Add success class
small.classList.add('success');
}
function login_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);
}
Is there an obvious mistake that I am not noticing?
Another problem I have is when the user enters values which are valid the form does't actually submit any values it because I have servers side php error handlers which are not activated after the form is submited which should be activated. For an example oner php error handler checks if the entered email is already in the database and this error handler wasn't activated even though I used an already used email address. Since I am using to stop the form from submitting before I check the input values preventDefault() and currentTargetSubmit() after I checked them should I use the currentTargetSubmit() for all the input values of a form?
The answer is actually very simple I just forgot to change the variables in my javascript code for the login modal from the variables in the javacript code for the sign up modal
I have created five input fields and a submit button to validate that fields but somehow it is not validated on submit.
In my JS I print the error dynamically. I have debugged by code and I get the proper values and errors, but it doesn't displays dynamically.
function seterror(id, error) {
// set error
var element = document.getElementById(id);
debugger;
console.log(element);
element.getElementsByClassName('ferror')[0].innerHTML = error;
}
function validateForm(e) {
e.preventDefault();
var returnval = true;
var name = document.forms['myForm']['fname'].value;
if (name.length < 5) {
seterror("uname", "abc");
returnval = false;
}
return returnval;
}
.ferror {
color: red;
}
<h1>Form Validation Demo</h1>
<form onsubmit="return validateForm()" name="myForm">
Name*: <input type="text" id="uname" name="fname"><b><span class="ferror"></span></b><br> Password*: <input type="password" id="pass" name="fpass"><b><span class="ferror"></span></b><br> Confirm Password*: <input type="password" id="cpassword" name="fcpass"><b><span class="ferror"></span></b> <br> Email*: <input type="email" id="uemail" name="femail"><b><span class="ferror"></span></b> <br> Phone*:
<input type="phone" id="uphone" name="fphone"><b><span class="ferror"></span></b> <br>
<input type="submit" class="btn" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Given all the comments under the question, here's my suggestion for a more flexible remake:
Don't use IDs for your fields
Use an additional <label> as wrapper
Don't bloat HTML with useless empty <span> error elements - create them using JS
Use a proper addEventListener() and use its Event in the Validation function
Use an errors array to store all the errors during each part of the validation
Only at the end, if the errors Array has items in it (meaning something is invalid) - in that case use Event.preventDefault() to prevent the form being submitted.
// Utility functions:
const EL = (sel, parent) => (parent || document).querySelector(sel);
const ELS = (sel, parent) => (parent || document).querySelectorAll(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
// Form validation script:
const EL_form = EL("#myForm");
const validateForm = (evt) => {
// Remove old errors
ELS(".ferror", EL_form).forEach(el => el.remove());
// Prepare an array to hold your errors
const errors = [];
// Get the desired fields:
const EL_fname = EL('[name="fname"]', EL_form);
const EL_fpass = EL('[name="fpass"]', EL_form);
const EL_fcpass = EL('[name="fcpass"]', EL_form);
const EL_femail = EL('[name="femail"]', EL_form);
const EL_fphone = EL('[name="fphone"]', EL_form);
// Validation and errors:
if (EL_fname.value.trim().length <= 4) {
errors.push({name: "fname", text: "Name is too short (min 4 chars)"});
}
if (EL_fpass.value.trim().length <= 8) {
errors.push({name: "fpass", text: "Password is too short (min 8 chars)"});
}
if (EL_fpass.value !== EL_fcpass.value) {
errors.push({name: "fcpass", text: "Passwords do not match"});
}
if (!/^.+#.+\./.test(EL_femail.value)) {
errors.push({name: "femail", text: "Invalid Email address"});
}
if (EL_fphone.value.trim().replace(/\D/g, "").length <= 6) {
errors.push({name: "fphone", text: "Invalid telephone number"});
}
// Show errors:
errors.forEach(err => {
const EL_error = ELNew("span", {
className: "ferror",
textContent: err.text,
});
EL(`[name="${err.name}"]`, EL_form).closest("label").append(EL_error);
});
// Prevent Form subnit on any error
if (errors.length) {
evt.preventDefault();
}
};
EL_form.addEventListener("submit", validateForm);
form label {
display: block;
}
.ferror {
color: red;
font-weight: 700;
}
<form id="myForm">
<label>Name: <input name="fname" type="text"></label>
<label>Password: <input name="fpass" type="password"></label>
<label>Confirm Password: <input name="fcpass" type="password"></label>
<label>Email: <input name="femail" type="email"></label>
<label>Phone: <input name="fphone" type="phone"></label>
<br>
<input type="submit" class="btn" value="Submit">
</form>
I am new to JavaScript and tend to get stuck with some problems. I was trying to create a custom validation for a form, which consists from 4 inputs, but the code doesn't work for me. Does anyone have any ideas how can I fix it? Here is just one of the inputs:
<div class="inputWrapper">
<input class="formInput required type="text" name="Email" id="Email" placeholder="Email Address"/>
<img class="errorImg hidden" src="/images/icon-error.svg" />
<div id="emailError" class="errorMessage hidden">
<i>Email cannot be empty</i>
</div>
</div>
I also have two divs that should appear, when the input is submitted with error, before that they have a class "hidden" with display none.
"use strict";
const formInput = document.querySelector(`.formInput`);
const errorImg = document.querySelector(`.errorImg`);
const errorMessage = document.querySelector(`.errorMessage`);
const input = formInput.nodeValue;
const errorOccured = function () {
errorMessage.classList.remove(`hidden`);
errorImg.classList.remove(`hidden`);
};
form.addEventListener("submit", function () {
if (input === ``) {
errorOccured();
}
});
This is how the page looks like itself:
You should read input value in the event listener function
let form = document.querySelector("#form1");
form.addEventListener("submit", function (e) {
const input = formInput.value;
if (input === '') {
errorOccured();
e.preventDefault();
}
});