form is getting submitted even after returing false - javascript

my script
<script>
function hii(Name,Mobile){
let Count=0;
if(Name=="" || Name==null){
document.getElementById('nameerror').style.display='block';
document.getElementById('nameerror').innerHTML='Please Enter Student Name';
Count++;
}
if(Mobile=="" || Mobile==null){
document.getElementById('mobileerror').style.display='block';
document.getElementById('mobileerror').innerHTML='Please Enter Student Mobile';
Count++;
}
if(Count>0){
alert(Count);
return false;
}
}
</script>
Html
<form action="addstudent.php" method="POST" onsubmit="hii(
document.getElementById('name').value,
document.getElementById('mobile').value
)">
<input type="text" name='name' id="name" placeholder="Enter Student Name"><br><br>
<label for="" id="nameerror" style="display: none;color:red;font-size:small;"></label>
<input type="number" name='mobile' id='mobile' placeholder="Enter Mobile Number"><br><br>
<label for="" id="mobileerror" style="display: none;color:red;font-size:small;"></label>
<input type="submit" value="add">
</form>
im getting count as 2 via alert after submitting form with no data which means there are no errors in my html and javascript code and i cant find any flashing errors in console

What you need is to pass an event to the submit function, and use event.preventDefault() to stop the submission.
function hii(event, Name, Mobile) {
let Count = 0;
if (Name == "" || Name == null) {
document.getElementById("nameerror").style.display = "block";
document.getElementById("nameerror").innerHTML =
"Please Enter Student Name";
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById("mobileerror").style.display = "block";
document.getElementById("mobileerror").innerHTML =
"Please Enter Student Mobile";
Count++;
}
if (Count > 0) {
event.preventDefault();
alert(Count);
}
}
<form
action="addstudent.php"
method="POST"
onsubmit="hii(
event,
document.getElementById('name').value,
document.getElementById('mobile').value
)"
>
<input
type="text"
name="name"
id="name"
placeholder="Enter Student Name"
/><br /><br />
<label
for=""
id="nameerror"
style="display: none; color: red; font-size: small"
></label>
<input
type="number"
name="mobile"
id="mobile"
placeholder="Enter Mobile Number"
/><br /><br />
<label
for=""
id="mobileerror"
style="display: none; color: red; font-size: small"
></label>
<input type="submit" value="add" />
</form>
A better solution is to use addEventListener()
document.querySelector("#form1").addEventListener("submit", hii);
function hii(event) {
const Name = document.querySelector("#name").value;
const Mobile = document.querySelector("#mobile").value;
let Count = 0;
if (Name == "" || Name == null) {
document.getElementById("nameerror").style.display = "block";
document.getElementById("nameerror").innerHTML =
"Please Enter Student Name";
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById("mobileerror").style.display = "block";
document.getElementById("mobileerror").innerHTML =
"Please Enter Student Mobile";
Count++;
}
if (Count > 0) {
event.preventDefault();
alert(Count);
}
}
<form
id="form1"
action="addstudent.php"
method="POST"
>
<input
type="text"
name="name"
id="name"
placeholder="Enter Student Name"
/><br /><br />
<label
for=""
id="nameerror"
style="display: none; color: red; font-size: small"
></label>
<input
type="number"
name="mobile"
id="mobile"
placeholder="Enter Mobile Number"
/><br /><br />
<label
for=""
id="mobileerror"
style="display: none; color: red; font-size: small"
></label>
<input type="submit" value="add" />
</form>

You have to return the value in the handler
<form action="addstudent.php" method="POST" onsubmit="return hii(
document.getElementById('name').value,
document.getElementById('mobile').value
)">
But better yet is to keep it all together in your script
<form action="addstudent.php" method="POST">
<!-- remove the onsubmit here -->
<input type="submit" value="add">
<!-- we'll put the listener here -->
Then, your script
document.querySelector('input[type="submit"]').addEventListener('click', function(e) {
e.preventDefault();
let Count = 0;
let Name = document.getElementById('name').value;
let Mobile = document.getElementById('mobile').value
if (Name == "" || Name == null) {
document.getElementById('nameerror').style.display = 'block';
document.getElementById('nameerror').innerHTML = 'Please Enter Student Name';
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById('mobileerror').style.display = 'block';
document.getElementById('mobileerror').innerHTML = 'Please Enter Student Mobile';
Count++;
}
if (Count > 0) {
alert(Count);
return false;
}
document.querySelector('form').submit()
})

Related

How can I get an animation to run when input submit is clicked in javascript?

I have a form which I want each time I validate if the information is empty, to run an animation of a library that imports from CSS called Animate.CSS, so I have created a function to validate each input, so if one is empty, it runs an "shake" animation of the library I mentioned. At the same time, the class has to be added, but removed at the end in case the user does not write in the input again, the animation runs.
This is my form:
<form action="" id="form">
<label for="name">Name</label>
<input
type="text"
placeholder="Name"
id="name"
minlength="3"
required
/>
<br />
<label for="email">Email</label>
<input type="email" placeholder="Emai" id="email" required />
<br />
<label for="subject">Subject</label>
<input
type="text"
placeholder="Subject"
id="subject"
minlength="3"
required
/>
<br />
<label for="message">Message</label>
<textarea
name="message"
id="message"
minlength="5"
placeholder="Message"
required
style="resize: none; height: 200px"
></textarea>
<br />
<button type="submit" class="paper-btn" id="submit">
Send message
</button>
</form>
And Javascript:
(function () {
var form = document.getElementById("form"),
name = form.name,
email = form.email,
subject = form.subject;
message = form.message;
function validateName(e) {
if (name.value == "" || name.value == null) {
form.classList.add("animate__animated");
name.classList.add("animate__shakeX");
e.preventDefaul();
} else {
console.log("error");
}
}
function validateEmail(e) {
if (email.value == "" || email.value == null) {
email.classList.add("animate__animated");
email.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateSubject(e) {
if (subject.value == "" || subject.value == null) {
subject.classList.add("animate__animated");
subject.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateMessage(e) {
if (subject.value == "" || subject.value == null) {
message.classList.add("animate__animated");
message.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateForm(e) {
validateName(e);
validateEmail(e);
validateSubject(e);
validateMessage(e);
}
form.addEventListener("submit", validateForm);
});
This code works, apparently, but it happens when I click on refresh and not when I click on submit:
var form = document.getElementById("name");
if (form.value == "" || form.value == null) {
form.classList.add("animate__animated");
form.classList.add("animate__shakeX");
}
There was a lot going on in there so I simplified some stuff to make a little more sense to me but you should go through your code and check for errors as there are quite a few there. I have made a little demo of what I assume you wanted the form to do.
document.getElementById("form").addEventListener("submit", (e) => {
validateName();
validateEmail();
validateSubject();
validateMessage();
e.preventDefault();
setTimeout(removeAnimations, "2000");
})
function validateName() {
const name = document.getElementById("name");
if(name.value.length < 3) {
name.classList.add("animate__red", "animate__animated");
} else {
name.classList.remove("animate__red");
}
}
function validateEmail() {
const ele = document.getElementById("email");
if(ele.value.length < 1) {
ele.classList.add("animate__red", "animate__animated");
} else {
ele.classList.remove("animate__red", "animate__animated");
}
}
function validateSubject() {
const ele = document.getElementById("subject");
if(ele.value.length < 3) {
ele.classList.add("animate__red", "animate__animated");
} else {
ele.classList.remove("animate__red", "animate__animated");
}
}
function validateMessage() {
const ele = document.getElementById("message");
if(ele.value.length < 3) {
ele.classList.add("animate__red", "animate__animated");
} else {
ele.classList.remove("animate__red", "animate__animated");
}
}
function removeAnimations() {
document.querySelectorAll(".animate__red")
.forEach((ele) => {
ele.classList.remove("animate__red", "animate__animated");
});
}
.animate__red {
background-color: red;
}
<form action="" id="form">
<label for="name">Name</label>
<input type="text" placeholder="Name" id="name" minlength="3" />
<br />
<label for="email">Email</label>
<input type="email" placeholder="Email" id="email" />
<br />
<label for="subject">Subject</label>
<input type="text" placeholder="Subject" id="subject" minlength="3" />
<br />
<label for="message">Message</label>
<textarea name="message" id="message" minlength="5" placeholder="Message" style="resize: none; height: 200px"></textarea>
<br />
<button type="submit" class="paper-btn" id="submit">
Send message
</button>
</form>

How can I add an animation on my HTML form when submit input is clicked and the input is empty on Javascript?

Basically, I'm coding a Javascript code that validate if a form is empty, so if one input is empty, it add an animation from Animate.css library. And if two inputs are empty, both will make the shake animation, if the whole form is empty, it will shake.
I've tried a global function with conditions that add a class and it doesn't work.
This is my form:
<form action="" id="form">
<label for="name">Name</label>
<input
type="text"
placeholder="Name"
id="name"
minlength="3"
required
/>
<br />
<label for="email">Email</label>
<input type="email" placeholder="Emai" id="email" required />
<br />
<label for="subject">Subject</label>
<input
type="text"
placeholder="Subject"
id="subject"
minlength="3"
required
/>
<br />
<label for="message">Message</label>
<textarea
name="message"
id="message"
minlength="5"
placeholder="Message"
required
style="resize: none; height: 200px"
></textarea>
<br />
<button type="submit" class="paper-btn" id="submit">
Send message
</button>
</form>
Javascript:
(function () {
var form = document.getElementById("form"),
name = form.name,
email = form.email,
subject = form.subject;
message = form.message;
function validateName(e) {
if (name.value == "" || name.value == null) {
form.classList.add("animate__animated");
name.classList.add("animate__shakeX");
e.preventDefaul();
} else {
console.log("error");
}
}
function validateEmail(e) {
if (email.value == "" || email.value == null) {
email.classList.add("animate__animated");
email.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateSubject(e) {
if (subject.value == "" || subject.value == null) {
subject.classList.add("animate__animated");
subject.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateMessage(e) {
if (subject.value == "" || subject.value == null) {
message.classList.add("animate__animated");
message.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateForm(e) {
validateName(e);
validateEmail(e);
validateSubject(e);
validateMessage(e);
}
form.addEventListener("submit", validateForm);
});
I think you just need to invoke the function. ValidateForm isn't being called
(function() {
var name = document.getElementById("name");
if (name.value == "" || name.value == null) {
name.classList.add("animate__animated");
name.classList.add("animate__shakeX");
}
})();

Why the output from javascript just shown for a short period of time?

I am developing a Registration form for my assignment. All things are working but when I click on the submit button, the warning messages on the label are just shown for a very short period of time. I am using eclipse and apache tomacat. here is my code.
JSP Code:
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid"/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname"/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname"/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email"/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" onclick="validate()"/>
</form>
Javascript Code:
function validate()
{
var itemid=document.getElementById("itemid").value;
var itemname=document.getElementById("itemname").value;
var uname=document.getElementById("uname").value;
var email=document.getElementById("email").value;
var amount=document.getElementById("amount").value;
var autoincrement=document.getElementById("autoincrement");
var flag=true;
if(itemid.length==0){
flag=false;
document.getElementById("itemid_l").innerHTML="<b>Required field!</b> Item Id: ";
}
if(itemname.length==0){
flag=false;
document.getElementById("itemname_l").innerHTML="<b>Required field!</b> Item Name: ";
}
if(uname.length==0){
flag=false;
document.getElementById("uname_l").innerHTML="<b>Required field!</b> Your Name: ";
}
if(email.length==0){
flag=false;
document.getElementById("email_l").innerHTML="<b>Required field!</b> Your Email Address: ";
}
if(amount.length==0){
flag=false;
document.getElementById("amount_l").innerHTML="<b>Required field!</b> Amount Bid: ";
}
if(!autoincrement.checked){
flag=false;
document.getElementById("autoincrement_l").innerHTML="<b>Required field!</b> Auto-increment to match other bidders:: ";
}
if(flag==true){
alert('Good job!!');
return true;
}
else
{
document.getElementById("msg").innerHTML="Required data is missing. Please fill";
return false;
}
}
Any suggestion will help me a lot..
You can use onsubmit event so that whenever user click on submit button this gets call and if the function validate() return true form will get submitted else it will not submit form .
Demo code :
function validate() {
var itemid = document.getElementById("itemid").value;
var itemname = document.getElementById("itemname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var amount = document.getElementById("amount").value;
var autoincrement = document.getElementById("autoincrement");
var flag = true;
if (itemid.length == 0) {
flag = false;
document.getElementById("itemid_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemid_l").innerHTML = ""
}
if (itemname.length == 0) {
flag = false;
document.getElementById("itemname_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemname_l").innerHTML = "";
}
if (uname.length == 0) {
flag = false;
document.getElementById("uname_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("uname_l").innerHTML = "";
}
if (email.length == 0) {
flag = false;
document.getElementById("email_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("email_l").innerHTML = "";
}
if (amount.length == 0) {
flag = false;
document.getElementById("amount_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("amount_l").innerHTML = "";
}
if (!autoincrement.checked) {
flag = false;
document.getElementById("autoincrement_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("autoincrement_l").innerHTML = "";
}
if (flag == true) {
document.getElementById("msg").innerHTML = "";
alert('Good job!!');
flag = true; //do true
} else {
document.getElementById("msg").innerHTML = "Required data is missing. Please fill";
flag = false; //do false
}
return flag; //return flag
}
<!--add onsubmit -->
<form method="post" id="forms" onsubmit="return validate()">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--give id to span instead of label-->
<label> <span id="itemid_l"></span>Item Id:</label> <input type="text" name="itemid" id="itemid" /><br/>
<label><span id="itemname_l"></span>Item Name:</label> <input type="text" name="itemname" id="itemname" /><br/>
<label><span id="uname_l"></span>Your Name:</label> <input type="text" name="uname" id="uname" /><br/>
<label><span id="email_l"></span>Your Email Address:</label> <input type="text" name="email" id="email" /><br/>
<label><span id="amount_l"></span>Amount Bid:</label> <input type="number" name="amount" id="amount" /><br/>
<label><span id="autoincrement_l"></span>Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" />
</form>
Also , if you just need to check for empty field you can just use required attribute on input tag like below :
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--added required attribute-->
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid" required/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname" required/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname" required/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email" required/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"required/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement" required><br/>
<input type="submit" value="Submit Bid"/>
</form>

Doing a web site with validation form

I currently trying to make a website with a validating booking form for a university a project about a university portal. It used to work with my javascript validation until I added to validate time. Problem is sumbit button not working when I add to validate time and whenever I remove it is working.
HTML and JavaScript
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Any suggestions?
You should do this kind of thing with required.
<input type="email" required>
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
(https://www.w3schools.com/tags/att_input_required.asp)
There also exist pattern. For example, if you want to allow only six letters
<input type="text" pattern="[A-Za-z]{6}" required>
Here's a stackoverflow question that gives more information.
As i can see, the problem isn't on validateDate but on validateWorkshop. If you try to submit a blank form, without choosing a workshop, reason.length gets value 5. But if you pick a workshop, reason.length gets 13.
Not that i recomend your validation but to get this working, i just added a var error = ""; at the begining of validateWorkshop.
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
var error = "";
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>

form not validating - javascript

bit of a noob with form validation. I'm trying to get this form to validate on the required fields, and something's amiss. Here's what I'm working with:
html:
<form action="../visit/thankyou.html" method="post" id="vsurvey">
<input type="hidden" name="id" value="503" />
<fieldset>
<legend>Group and Coordinator Information</legend>
<label><span>Group Leader Name<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8149" />
</label>
<label><span>Email<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8155" />
</label>
<label><span>Phone<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8156" />
</label>
<label><span>School/Organization<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8159" />
</label>
<label><span>Program</span>
<input type="text" name="question_8180" />
</label>
<label><span>Grade(s)</span>
<input type="text" name="question_8181" />
</label>
<label><span>Number of Participants<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8182" />
</label>
</fieldset>
<fieldset>
<label><span>Preferred Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8185" name="question_8185" />
</label>
<label><span>Second Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8186" name="question_8186" />
</label>
<label><span>Third Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8187" name="question_8187" />
</label>
<label>Special Accommodations
<input type="text" name="question_8174" />
</label>
</fieldset>
<label>What is the purpose or desired outcome of this visit?
<textarea name="question_13026"></textarea>
</label>
<label>How did you learn about our Group Visit Program?
<textarea name="question_8176"></textarea>
</label>
<label>Comments
<textarea name="question_8184"></textarea>
</label>
<input type="submit" id="sbutton" value="Submit Request" />
</form>
js:
function validateForm() {
var x = document.forms["vsurvey"]["question_8149"].value;
if (x == null || x == "") {
alert("Please fill in the Group Leader's name.");
return false;
}
var x = document.forms["vsurvey"]["question_8155"].value;
if (x == null || x == "") {
alert("Please fill in the email field.");
return false;
}
var x = document.forms["vsurvey"]["question_8156"].value;
if (x == null || x == "") {
alert("Please fill in the phone field.");
return false;
}
var x = document.forms["vsurvey"]["question_8159"].value;
if (x == null || x == "") {
alert("Please fill in the School/Organization field.");
return false;
}
var x = document.forms["vsurvey"]["question_8182"].value;
if (x == null || x == "") {
alert("Please indicate the number or participants.");
return false;
}
var x = document.forms["vsurvey"]["question_8185"].value;
if (x == null || x == "") {
alert("Please enter your preferred date.");
return false;
}
var x = document.forms["vsurvey"]["question_8186"].value;
if (x == null || x == "") {
alert("Please enter your second date preference.");
return false;
}
var x = document.forms["vsurvey"]["question_8187"].value;
if (x == null || x == "") {
alert("Please enter your third date preference.");
return false;
}
}
http://jsfiddle.net/blackessej/9a6BJ/1/
Currently the form submits the info anyway, but without sending the user to the thankyou page, if all required fields aren't filed in. If all required fields are filed, the thankyou page gets called.
You're not calling validatorForm. Your input button needs to be the following
<input type="submit" id="sbutton" value="Submit Request" onclick="return validateForm()" />
Or use the onsubmit event of your form
<form action="../visit/thankyou.html" method="post" id="vsurvey" onsubmit="return validateForm()">
You need to create an onSubmit event to call validateForm:
document.getElementById('vsurvey').onsubmit = validateForm;

Categories