Form submission validation: Why it is not showing pop up message that fill out required entries in form if empty - javascript

I am running with this problem where I am clicking the submit button but it is not showing that particular entry like "fname,email,message" are required.
I have tried different ways like putting "required" attribute in input tags but here also same thing is happening.
This is contact.html file:
<script defer src="script.js"></script>
<div id="error"></div>
<div class="con"><div class="he"><h1>Contact Us</h1><br>
<p>Please feel free to contact us with any questions you may have around our coaching or online analysis. </p></div> </div> -->
<div class="con2"> <div class="form"><form class="form" name="myform" method="GET">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" class="name1">
<label for="lname"class="n">Last name:</label>
<input type="text" id="lname" name="lname" class="name2"><br>
<label for="email">Email:</label><br>
<input type="text" id="mail2" name="email"class="mail"><br>
<label for="comment">Message or Comment:</label><br>
<textarea name="comment" rows="10" cols="30"class="para">
</textarea><br>
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
script.Js file:
const name=document.getElementsByClassName('name1')
const name2=document.getElementsByClassName('name2')
const mail=document.getElementsByClassName('mail')
const para=document.getElementsByClassName('para')
const form=document.getElementsByClassName('form')
const errorElement=document.getElementById('error')
form.addEventListener('submit' , (e)=>{
let messages = [] if (name1.value == =''|| name1.value == null) {
messages.push('Name is required')
}
if (mail.value == =''|| mail.value == null) {
messages.push('Mail is required')
}
if (para.value == =''|| para.value == null) {
messages.push('Message is required')
}
if (messages.length > 0) {
e.preventDefault() errorElement.innerText = messages.join(', ')
}
})

Please use an id for your <form> element, because class="form" is repeated for both, the <form> tag and the <div> tag wrapping the <form>.
I've cleaned up your code, so try the following:
const form = document.getElementById('form');
const fname = document.getElementById('fname');
const lname = document.getElementById('lname');
const mail = document.getElementById('mail');
const message = document.getElementById('message');
const errorElement = document.getElementById('error');
form.addEventListener('submit', (e) => {
let messages = [];
if (fname.value === '' || fname.value == null) {
messages.push('Name is required');
}
if (mail.value === '' || mail.value === null) {
messages.push('Mail is required');
}
if (message.value === '' || message.value === null) {
messages.push('Message is required');
}
if (messages.length > 0) {
e.preventDefault();
errorElement.innerText = messages.join(', ');
}
})
<div id="error"></div>
<div class="con2">
<form id="form" name="myform" method="GET">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" class="name1">
<label for="lname" class="n">Last name:</label>
<input type="text" id="lname" name="lname" class="name2"><br>
<label for="email">Email:</label><br>
<input type="text" id="mail" name="email" class="mail"><br>
<label for="comment">Message or Comment:</label><br>
<textarea name="comment" rows="10" cols="30" id="message"></textarea><br>
<button type="submit">Submit</button>
</form>
</div>

Related

How to make an error message for each empty form field

I am trying to display an error message for each empty field, my problem is that when I submit the form with an empty (one or two) field all the error messages appear. I want only one error message for each empty field to appear, not all of them.
HTML :
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
JavaScript:
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
e.preventDefault();
const firstName = document.getElementById("name");
const lastName = document.getElementById("last-name");
const email = document.getElementById("email");
const password = document.getElementById("password");
if(firstName.value < 1 ) {
errorField.forEach((f) => f.classList.toggle('error-active'));
errorField.forEach((c) => c.style.color = "red");
firstName.classList.toggle("invalid");
return false;
}
if (lastName.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
lastName.classList.toggle("invalid");
return false;
}
if (email.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
email.classList.toggle("invalid");
return false;
}
if (password.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
password.classList.toggle("invalid");
return false;
} else {
password.classList.remove("invalid");
errorField.classList.remove("error-active");
}
return true;
}
submitButton.addEventListener('click' , validate);
Hope this fixed your issue. Notice, password changed to passwordD and you were accessing all the error field without specifying which
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
e.preventDefault();
const firstName = document.getElementById("name");
const lastName = document.getElementById("last-name");
const email = document.getElementById("email");
const passwordD = document.getElementById("password");
if (firstName.value < 1) {
errorField[0].classList.toggle('error-active');
errorField[0].style.color = "red";
firstName.classList.toggle("invalid");
}
if (lastName.value < 1) {
errorField[1].classList.toggle("error-active");
errorField[1].style.color = "red";
lastName.classList.toggle("invalid");
}
if (email.value < 1) {
errorField[2].classList.toggle("error-active");
errorField[2].style.color = "red";
email.classList.toggle("invalid");
}
if (password.value < 1) {
errorField[3].classList.add("error-active");
errorField[3].style.color = "red";
passwordD.classList.toggle("invalid");
} else {
passwordD.classList.remove("invalid");
errorField.forEach((f) => {
f.classList.remove("error-active");
f.style.color = "black";
});
return true;
}
return false;
}
submitButton.addEventListener('click', validate);
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
I would suggest you to use a form validation JS plugin instead of reinveting the wheel, for example Form Validation Plugin
You can simplify your code a bit using a class for the inputs, and keeping track of an isValid boolean for the form. You were setting all error-fields with your code. Here, we are able to reference just the error-field that applies using closest() to find the encompassing label, then querySelector to find the error-field
el.closest('label').querySelector('.error-field');
const submitButton = document.querySelector('.form-button');
const validate = (e) => {
e.preventDefault();
let isValid = true
document.querySelectorAll('.validate').forEach(el => {
let error = el.closest('label').querySelector('.error-field').classList;
if (el.value.trim().length === 0) {
isValid = false;
error.add('error-active');
el.classList.add('invalid')
} else {
error.remove('error-active');
el.classList.remove('invalid')
}
})
return isValid;
}
submitButton.addEventListener('click', validate);
.error-field.error-active,
input.invalid{
color: #f00;
}
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" class='validate' name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" class='validate' name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" class='validate' name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" class='validate' name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
That's because inside each if statement you are looping through all the Error fields in the form and update it all. So what you can do is first add unique id for each dom entry in the HTML file such as err-password, error-name and so on then inside each if statement grab the relevant eror field that needs to show the error and update only that field.
Using nextElementSibling would simplify your code a lot here... Since the error message always is right after the input.
In the condition to show or not the error.. That is the value.length you have to check.
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
// Remove any already displayed error
errorField.forEach(function(error){
error.classList.remove("invalid");
})
// Loop through all inputs to check the value length
document.querySelectorAll("form input").forEach(function(input){
if(input.value.length < 1){
input.nextElementSibling.classList.toggle("invalid");
}
})
// Prevent submit only if there are errors shown
let errorCount = document.querySelectorAll(".error-field.invalid").length
if(errorCount){
e.preventDefault();
}
}
submitButton.addEventListener('click' , validate);
label{
display: block;
}
label p{
margin: 0;
}
.error-field{
display: none;
color: red;
}
.invalid{
display: inline-block;
}
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>

html form validation using javascript

i am trying to validate my html form using javascript. the validation works but it still submits.
ie. when clicking submit a text will appear saying "first name is required" but then still submits.
here is the javascript code:
function validateForm(form) {
formValid = true;
for(i = 0; i < form.length; i++) {
if(!requiredInput(form[i]))
formValid = false;
}
return formValid;
}
function requiredInput(element) {
if(!element.value.length) {
document.getElementById(element.id + 'Error').style.display = "inline-block";
return false;
} else {
document.getElementById(element.id + 'Error').style.display = "none";
return true;
}
return;
}
and here is the html code for the form:
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get" onsubmit="return validateForm(this);">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
</form>
im not sure why it still submits.
EDIT: i need to debug this code and not change all of it
EDIT: i can not change the html code for this, i am to debug the javascript only
I think you need validate if its type submit :
function validateForm(form) {
formValid = true;
for(i = 0; i < form.length; i++) {
if(form[i].type != "submit"){
if(!requiredInput(form[i])){
formValid = false;
}
}
}
return formValid;
}
Your validation has the correct structure, however, if there is any JavaScript error, the "return false" will not cancel the form submission.
Go to your developer console and manually invoke the validateForm function. You can give the form an ID:
<form id="myform"...
Then, you can reference this in the console:
validateForm(document.getElementById('form'));
You will see a JavaScript error. Fix the error and your form will be intercepted.
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get"
onsubmit="return validateForm(event)">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit">
</div>
<script type="text/javascript">
function validateForm(e) {
form = e.target;
formValid = true;
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i]))
formValid = false;
}
return formValid;
}
function requiredInput(element) {
if (element.type == 'submit') {
return true;
}
if (element.value.length == 0) {
document.getElementById(element.id + 'Error').style.display = "inline-block";
return false;
} else {
document.getElementById(element.id + 'Error').style.display = "none";
return true;
}
}
this should work
Actually You can do it simple way, see below,
Modify your HTML
I remove onsubmit attribute and add form to ID
<form id="dsds" action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
Remove your JS function and do like this,
$("#dsds").submit(function(e){
//call your functions here
return false; // return true if you want to submit the form
});
See the example,
JSFille
Use preventDefault() to disable the submit.
function validateForm(event, form) {
formValid = true;
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i])) {
formValid = false;
break;
}
}
if (!formValid) {
event.preventDefault();
}
return formValid;
}
And pass the event object in the onsubmit function like below.
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get" onsubmit="validateForm(event, this);">
function validateForm(form) {
formValid = true;
try {
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i]))
formValid = false;
}
} catch (error) {
console.error("validateForm=>", error)
}
return formValid;
}
function requiredInput(element) {
try {
const elementInputError = document.getElementById(element.id + 'Error');
if (!element.value.length) {
elementInputError && setDisplayError(elementInputError,"inline-block");
return false;
} else {
elementInputError && setDisplayError(elementInputError,"none");
return true;
}
} catch (error) {
console.error("requiredInput=>", error)
return false;
}
}
function setDisplayError(element,value) {
try {
element.style.display =value;
} catch (error) {
console.error("setDisplayError=>", error)
}
}
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get"
onsubmit="return validateForm(this);">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit">
</div>
</form>
The problem arose because it also validated the send button and because it did not have the termination of the failed id it could not find the item and an error occurred. Then when the error occurred it did not return anything the function and redirect you to the form action page.

Javascript Validation form onsubmit not returning false

Note : i searched similar questions and still couldn't fix it so i'm asking again.
i have a form and its onsubmit = "return submit()". it checks if textarea is empty. If it is then it returns false but that doesn't work.The action still goes to the next website even if text area is empty.
let firstName = document.querySelector('#firstname');
let lastName = document.querySelector('#lastname');
let password = document.querySelector('#password');
let retypePass = document.querySelector('#repassword');
let radioMale = document.querySelector('#male');
let radioFemale = document.querySelector('#female');
let textArea = document.querySelector('#textarea');
let select= document.querySelector('#select');
let button = document.querySelector('#button');
let form = document.querySelector('#form');
function submit(){
if (textArea.value = "") {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
}
HTML :`
<div class='wrapper'>
<h1>Registration Form</h1>
<form action="http://google.com" id='form' onsubmit="return submit()">
<input placeholder="First Name" type="text" id='firstname' required>
<span></span>
<br>
<input placeholder="Last Name" type="text" id='lastname' required>
<span></span>
<br>
<input placeholder="Password" type="text" id='password' required>
<span></span>
<br>
<input placeholder="Retype Password" type="text" id='repassword' required>
<span></span>
<br>
<input placeholder="Phone Number" type="tel" id='tel' >
<br>
<div class='radio'>
<h4>Selector Your Gender</h4>
<input type='radio'name='same' id='male'>Male
<input type='radio'name='same' id='female'>Female
</div>
<p style="margin:5px 0px;color:white">ADDRESS:</p>
<textarea id='textarea'></textarea>
<span></span>
<p style="margin:5px 0px;color:white">Country:</p>
<select type='country' style="width:84%" id='select'>
<option>England</option>
<option>Japan</option>
<option>America</option>
<option>France</option>
<option>NetherLands</option>
</select>
<br><br>
<input type='submit' value='submit'>
</form>
</div>
Your if systax was wrong:
if (textArea.value = "")
It should be:
if (textArea.value == "")
You must change the name of the function
Example
<form action="http://google.com" id='form' onsubmit="return validate()">
and
function validate() {
if (textArea.value == "") {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
}
try
if (!textArea.value) {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}
OR
if (textArea.value == '') {
textArea.nextElementSibling.innerHTML = "Fill this box";
return false;
}

My register form keeps refreshing the page

on my local server it works just fine but as soon as I take it live it starts only refershing the page instead of calling the validation.
This is my jquery:
<script>
$("form#registerform").submit(
function (e) {
e.preventDefault();
function validateForm() {
var RegisterUsername = document.forms["contactForm"]["RegisterUsername"].value;
var FirstName = document.forms["contactForm"]["FirstName"].value;
var LastName = document.forms["contactForm"]["LastName"].value;
var Email = document.forms["contactForm"]["Email"].value;
var RegisterPassword = document.forms["contactForm"]["RegisterPassword"].value;
if (RegisterUsername == null || RegisterUsername == "") {
$(".error-messages").text("Username required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (FirstName == null || FirstName == "") {
$(".error-messages").text("First name required").fadeIn(300).delay(1000).fadeOut(300);
return false;
} else if (LastName == null || LastName == "") {
$(".error-messages").text("Last name required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (Email == null || Email == "") {
$(".error-messages").text("Email required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (RegisterPassword == null || RegisterPassword == "") {
$(".error-messages").text("Password required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
}
}
</script>
This is my html:
<form id="registerform" name="contactForm" action="" onsubmit="return validateForm()" method="post">
<div class="pl-land-input">
<input class="email text-input" id="RegisterUsername" pattern=".{3,}" title="3 characters minimum" name="RegisterUsername" placeholder="Username" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" id="FirstName" name="FirstName" placeholder="First Name" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" id="LastName" name="LastName" placeholder="Last Name" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" type="email" placeholder="Email" name="Email" id="Email">
</div>
<div class="pl-land-input">
<input class="email text-input" id="RegisterPassword" name="RegisterPassword" placeholder="Password" type="password">
</div>
<button type="submit" value="Submit" class="signup-plland">Sign up</button>
</form>
I have been trying to get my head around it and kept customizing it but I couldn't figure out the problem there was no problem in console for calling the Jquery libs.
I hope I can solve this asap.

Validation fails when multiple <form> tags are present in the same HTML document

I have multiple form tags in my html doc and want to validate them. However the validation function won't give any result. Tried
adding name field to the <form> the validation() does not return any result.
When I use validation with only one <form> the result is correct.
here are the two form tags:
<div id="pinfo">
<form>
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="Enter name">
<br><br>
Email:
<input type="email" name="eamil" value="Enter email id">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
</fieldset>
</form>
</div>
<div id="linfo">
<form>
<fieldset>
<legend>Location and Contact</legend>
Location:
State:
<!more code ahead>
<script>
function validateForm() {
var eid = document.forms["loginform"]["emailid"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["password"].value;
if (pwd == null || pwd == ""){
alert("Please enter the password.");
return false;
}
var p = document.forms["locinfo"]["pno"].value;
if (p == null || p=="") {
alert("Please enter the phone no.");
return false;
}
</script>
Validating Form Fields Using JavaScript in FrontPage
There are some mistakes in your code.
You have not given form name as "loginform" which you are using in validation function.
And second thing you missed is "onsubmit" attribute on form element
Here is working code for you
function validateForm() {
console.log(document.forms["loginform"])
var eid = document.forms["loginform"]["eamil"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["pass"].value;
if (pwd == null || pwd == "") {
alert("Please enter the password.");
return false;
}
/*var p = document.forms["locinfo"]["pno"].value;
if (p == null || p == "") {
alert("Please enter the phone no.");
return false;
}*/
}
<div id="pinfo">
<form method="post" name="loginform" action="/" onsubmit="return validateForm()">
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="">
<br><br>
Email:
<input type="email" name="eamil" value="">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
<input type="submit" name="submit" />
</fieldset>
</form>
</div>

Categories

Resources