How to make sure if everything is valid before submitting? - javascript

I have a HTML5 form and I'm using javascript to validate the form.
I have several 'if's checking the form and if it valid they change a variable ('pass') to true or false. They also display an error message. The problem is that even if just one thing is valid it changes the variable is true and I need it to only make pass true if everything else is valid.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<div>
<form name="register" action="register.php" method="POST" >
<label>First Name:</label>
<input type="text" id="firstName" name="firstName"><br />
<label id="warning_first"></label>
<br />
<label>Surname:</label>
<input type="text" id="lastName" name="lastName"><br />
<label id="warning_second"></label>
<br />
<label>Gender:</label>
<input type="radio" name="gender" value="Male" id="male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Other">Other
<input type="radio" name="gender" value="Prefer not to say"> Prefer not to say <br />
<label id="warning_third"></label>
<br />
<label>Email:</label>
<input type="email" id="email" name="email"> <br />
<label id="warning_fourth"></label>
<br />
<label>Confirm Email:</label>
<input type="email" id="confirmEmail" name="confirmEmail">
<br />
<label>Mobile:</label>
<input type="tel" id="mobileNumber" name="mobileNumber">
<br />
<label>Telephone:</label>
<input type="tel" id="telephoneNumber" name="telephoneNumber">
<br />
<input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();">
<input type="button" name="submit" value="Register" onclick="submitCheck();">
</form>
<script src="script.js"></script>
</div>
</body>
</html>
My JavaScript:
function submitCheck() {
var pass = false;
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var genderTest = document.getElementsByName("gender");
var genderIf = false;
for (var a = 0; a < genderTest.length; a += 1) {
if (genderTest[a].checked) {
genderIf = true;
}
}
var emailCheck = document.getElementById("email").value;
if (firstName.length > 0) {
document.getElementById("warning_first").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_first").innerHTML = "This is required!";
pass = false;
}
if (lastName.length > 0) {
document.getElementById("warning_second").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_second").innerHTML = "This is required!";
pass = false;
}
if (genderIf) {
document.getElementById("warning_third").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_third").innerHTML = "This is required!"
pass = false;
}
if (emailCheck.length > 0) {
document.getElementById("warning_fourth").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_fourth").innerHTML = "Your email is too short!";
pass = false;
}
if (pass) {
console.log("OK");
} else {
console.log("NO");
}
}
As you can see, if the email is true, the console will log "OK" (which I am using to see if everything is valid"). How can I solve this so that it doesn't 'pass' to true if just the email is valid?
I am using a normal button instead of a submit button because of issues with the #onsubmit.

At the moment, you default pass to false and change it to true if any element passes the test.
Reverse your logic.
Set the default value of pass to true. Change it to false if any element fails its test.

Its simple, at the start of your code change your pass variable to have a value of 1 like so:
var pass = 1;
Now change the line of code in your IF statements where you have your pass variable. For a true condition set to this:
pass *= 1;
And for a false condition to this
pass *= 0;
This ensures that unless all IF conditions are satisfied your pass variable will not return a true state.

Related

Why is my exception handling not catching?

This is my html code that I am trying to create the exception handling for. I am trying to create the exceptions for the first form in this code.
<form id="survey" name="survey" method="post">
<div id="errorText"></div>
<fieldset class="labelfloatleft" id="contactinfo"><legend>Your Thoughts</legend>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<label for="emailaddress">Email Address</label>
<input type="email" name="emailaddress" id="emailaddress"
size="30" placeholder="foryou#yahoo.com" />
</fieldset>
<fieldset><legend>Best Movie</legend>
<input type="radio" name="movie" id="horror" value="horror" checked="checked"/>
<label for="horror">The Horror</label>
<input type="radio" name="movie" id="badabing" value="badabing" />
<label for="badabing">Bada-Bing Bada-Boom</label>
<input type="radio" name="movie" id="roll" value="roll" />
<label for="roll">Roll or Die</label>
</fieldset>
<fieldset><legend>Comments</legend>
<label for="message">Your Opinion</label>
<textarea name="message" id="message" rows="7" cols="30"></textarea>
</fieldset>
<input type="submit" value="Send" class="button" id="submitBtn"/>
<input type="reset" value="Cancel" class="button" />
</form>
<h2>Welcome To Our World</h2>
<p class="very">We are a small time movie theater looking to help inspire
people who come to our theater. Our theaters come with
fresh food, cold and hot drinks, souvenirs and comfortable
seats to help make your experience worth while.
</p>
<h2>Most Popular</h2>
<ul>
<li>The Horror</li>
<li>Bada-Bing Bada-Boom</li>
<li>Roll or Die</li>
</ul>
<h2>Prices</h2>
<table title="prices">
<tr>
<th>Ticket</th>
<th>Price</th>
<th>Thursday Deal</th>
</tr>
<tr>
<td>Adult</td>
<td>$10.00</td>
<td rowspan="3">Half-Off</td>
</tr>
<tr>
<td>Child</td>
<td>$6.00</td>
</tr>
<tr>
<td>Senior</td>
<td>$8.00</td>
</table>
<form id="price" name="price" method="post">
<fieldset><legend>Ticket Quantity</legend>
<label for="adultinput">Adult 15-60
<input type="text" id="adultinput" value="1" size="2"/>
</label>
<label for="childinput">Child 1-14
<input type="text" id="childinput" value="0" size="2"/>
</label>
<label for="seniorinput">Senior 50 and up
<input type="text" id="seniorinput" value="0" size="2"/>
</label>
</fieldset>
<input type="submit" value="Calculate" id="calculate" class="button" />
<input type="reset" value="Cancel" class="button" />
</form>
This is my exception handling code that I am trying to get working. However, no matter how much I modify it, it never shows correctly. I have ran it in Chrome and have tried using a debugger to help however I am still unable to show the exceptions when I click the submit button.
"use strict";
var fnameComplete = true;
var lnameComplete = true;
var emailComplete = true;
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
var errorDiv = document.getElementById("errorText");
function verifyFname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(fname.value)) || (fname.value === "")){
fname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
fnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyLname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(lname.value)) || (lname.value === "")){
lname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
errorDiv.style.display = "block";
lnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyEmail() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(email === "") {
email.style.background = "rgb(255,233,233)";
throw "Please enter your email.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
emailComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function validateForm(e) {
if (e.preventDefault) {
e.preventDefault(); //prevent form from submitting
} else {
e.returnValue = false; //prevent form from submitting in IE8
}
formValidity = true; //reset value for revalidation
verifyEmail();
verifyFname();
verifyLname();
if(formValidity === true) {
document.getElementsByTagName("form")[0].submit();
}
}
function createEventListeners() {
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener){
form.addEventListener("submit", validateForm, false);
} else if(form.attachEvent) {
form.attachEvent("onsubmit", validateForm);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
} else if(window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
It looks like you try to access a non existing field.
Here you already get the values of the fields
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
And in your comparisons you try to access a value field again. But you already have the plain value
if(!(isNaN(lname.value)) || (lname.value === "")){
}
Do it this way instead
if(!(isNaN(lname)) || (lname === "")){
}

JQuery HTML form validation still triggers email with blank entries

I have an HTML form with three mandatory fields in. I don't want the form to submit the AJAX call if they are empty.
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid = true;
if( $('input[name="Name"]').val() == '' || $('input[name="Email"]').val() == '' || $('input[name="Phone"]').val() == '') {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
<form id="contact" name="contact" method="post" action="">
<label for="Name">Name: *</label>
<input type="text" name="Name" id="name" />
<input name="robotest" type="hidden" value="" />
<label for="Position">Position:</label>
<input type="text" name="Position" id="position" />
<label for="Company">Company:</label>
<input type="text" name="Company" id="company" />
<label for="Address">Address:</label>
<input type="text" name="Address" id="address" />
<label for="Email">Email: *</label>
<input type="text" name="Email" id="email" />
<label for="Email">Phone number: *</label>
<input type="text" name="Phone" id="phone" />
<label for="Event_Subject">What is the subject of the event?:</label>
<input type="text" name="Event_Subject" id="subject" />
<label for="Event_Date">What is the date of the event?:</label>
<input type="text" name="Event_Date" id="date" />
<label for="Additional_info">Additional Information:</label>
<br />
<textarea name="Additional_info" rows="20" cols="20" id="info"></textarea>
<input id="formsubmitted" type="submit" name="submit" value="submit" class="submit-button" />
</form>
This does give the popup box if you try and fill it in empty, but I have received an email with all blank fields.
How is the user getting past the validation and managing to send the form through blank?
More than likely you've not popped in a preventDefault() in there, so the form is doing a normal (non-AJAX) post after your function ends. What's the method/action on your form? Perhaps there doesn't need to be an action at all?
Try this:
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
} else {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
As Jigar pointed out, you can shorten the code by assigning an initial value to the valid variable and removing else block:
var valid = false;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
}

Show me if all inputs are empty

I need to build such that all four inputs must be specified any such if there is nothing in the name so it must appear that the it is as trouble is that nothing is written in the name.
I want to want out of this is that I will not have to use such can just create a user or send an email but it must have written something in every input form.
I have done like this:
<form action="#" method="post" name="kontakt_box">
<span id="myhint" class="info_box_kontakt"></span>
<br />
<label>Navn<br /><input type="text" name="navn" class="new" placeholder="Navn"></label><br />
<label>Efternavn<br /><input type="tel" name="efternavn" class="new" placeholder="Efternavn"></label><br />
<label>Email<br /><input type="email" name="email" class="new" placeholder="Email"></label><br />
<label>Tekst<br /><textarea name="tekst" cols="35" rows="10" class="new"></textarea></label><br />
<label><input type="submit" name="send" value="Send" class="new"></label>
</form>
Javascript here:
document.kontakt_box.navn.onfocus=function() {
document.getElementById('myhint').innerHTML = "Angive et navn!";
}
document.kontakt_box.navn.onblur=function() {
document.getElementById('myhint').innerHTML = "";
}
//efternavn
document.kontakt_box.efternavn.onfocus=function() {
document.getElementById('myhint').innerHTML = "Angive et efternavn!";
}
document.kontakt_box.efternavn.onblur=function() {
document.getElementById('myhint').innerHTML = "";
}
//email
document.kontakt_box.email.onfocus=function() {
document.getElementById('myhint').innerHTML = "Angive en email!";
}
document.kontakt_box.email.onblur=function() {
document.getElementById('myhint').innerHTML = "";
}
document.kontakt_box.send = function(){
alert('Husk noget tekst!');
return false;
}
it's my first javasciprt task to a page, so you just better with me that there may be errors or you think it's strange made​​.
Your last function may be something like this:
document.kontakt_box.onsubmit = function(){
var navn = document.kontakt_box.navn.value,
efternavn = document.kontakt_box.efternavn.value,
email = document.kontakt_box.email.value,
tekst = document.kontakt_box.tekst.value;
if(!navn || !efternavn || !email || !tekst) {
alert('Husk noget tekst!');
return false;
}
};
And add ; afret each callback function assignment.
Working example here http://jsbin.com/enovex/1/edit

Combining javascript functions

hi i am using javascript function to balnk ma textboxes when its clicked, initially the text boxes contain their respective label names, eg: Client Name, Company etc. When the text box is clicked it makes the text box empty so data can be types. for this i am using a javascript function and for each textbox i have to have a seperate function, can anyone tell me how i can combine all these function, the only different thing in each function is the value used in the textbox and the textbox name.
The Javascript function
function clientnameclear() {
if(document.bunkerfrm.clientname.value=="Client Name") {
var bunkerfrm = document.bunkerfrm.clientname.value="";
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
}
function clientnamereset() {
if(document.bunkerfrm.clientname.value=="") {
var bunkerfrm = document.bunkerfrm.clientname.value="Client Name";
}
}
function vesselnameclear() {
if(document.bunkerfrm.vesselname.value=="Vessel Name") {
var bunkerfrm = document.bunkerfrm.vesselname.value="";
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
}
function vesselnamereset() {
if(document.bunkerfrm.vesselname.value=="") {
var bunkerfrm = document.bunkerfrm.vesselname.value="Vessel Name";
}
}
function compclear() {
if(document.bunkerfrm.company.value=="Company") {
var bunkerfrm = document.bunkerfrm.company.value="";
var bunkerfrm = document.bunkerfrm.company.focus();
}
else {
var bunkerfrm = document.bunkerfrm.company.focus();
}
}
function compreset() {
if(document.bunkerfrm.company.value=="") {
var bunkerfrm = document.bunkerfrm.company.value="Company";
}
}
The Html Code is
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" class="txtbox" value="Client Name" onmousedown="clientnameclear()" onclick="clientnameclear()" onblur="clientnamereset()" />
<br /><br>
<input type="text" name="company" class="txtbox" value="Company" onmousedown="compclear()" onclick="compclear()" onblur="compreset()" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
First, store the default values somewhere, such as the alt of the given input.
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" alt="Client Name" class="txtbox" value="Client Name" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="text" name="company" class="txtbox" alt="Company" value="Company" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
Then pass the input element this as the parameter to these onfocus/onblur functions:
function clear_text(elem)
{
if (elem.value == elem.alt)
elem.value = "";
}
function reset_text(elem)
{
if (elem.value == "")
elem.value = elem.alt;
}
Which will clear the input when it gets focus if its value is the same as the placeholder stored in the alt attribute. The event onblur will trigger the reset_text function which will check if the value is empty and restore it to the default placeholder stored in the alt attribute.
Use placeholder:
<input type="text" name="clientname" placeholder="Client Name" class="txtbox" />
<br /><br>
<input type="text" name="company" class="txtbox" placeholder="Company" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" placeholder="Send Your Inquiry" /><br>
</form>
I suggest you use and/or study existing libraries, such as:
In-Field http://fuelyourcoding.com/scripts/infield/
ClearField http://labs.thesedays.com/projects/jquery/clearfield/

Validating radio buttons by their boolean values?

I want to avoid using a for loop to validate a set of radio buttons. I know that its possible to use their boolean value to do this I just cannot seem to execute it. Is there a better way to do this?
Here are my buttons:
<form method="post" name="newUser" onsubmit="return proc()">
First name:<br />
<input type="text" id="fName" /><br />
<div id="first_name_error"></div>
Last name:<br />
<input type="text" name="lName" /><br />
<div id="last_name_error"></div>
E-mail address:<br />
<input type="text" name="eMail" /><br />
<div id="email_error"></div>
Gender:<input type="radio" name"sex" value="male" />Male
<input type="radio" name="sex" value="female" />Female<br />
<div id="gender_error"></div>
Here is my JS:
function proc(){
var errmsg = "";
if (document.forms["newUser"]["fName"].value == "")
{
document.getElementById('first_name_error').innerHTML = "*This field is required";
document.getElementById('first_name_error').style.color = "red";
}
if (document.forms["newUser"]["lName"].value == "")
{
document.getElementById('last_name_error').innerHTML = "*This field is required";
document.getElementById('last_name_error').style.color = "red";
}
if (document.forms["newUser"]["eMail"].value == "")
{
document.getElementById('email_error').innerHTML = "*This field is required";
document.getElementById('email_error').style.color = "red";
}
if (document.forms["newUser"].sex == false)
{
document.getElementById('gender_error').innerHTML = "*Please select gender";
document.getElementById('gender_error').style.color = "red";
}
return false;
}
I think you'd better assign two ids to two radio buttons (radbtnMale, radbtnFemale for example)
Then check:
if (document.getElementById("radbtnMale").checked == false && document.getElementById("radbtnFemale").checked == false) {
document.getElementById('gender_error').innerHTML = "*Please select gender";
document.getElementById('gender_error').style.color = "red";
} else {
//
}
Try this (jQuery):
if($('input[name=n]:checked').length==0){
//error
}else{
//OK
}

Categories