HTML javascript valIdation not working - javascript

I have this html with javascript validation form, but I don't know why it's not working. It's right now supposed to calculate the values of the two textboxes when the button is pressed. However nothing is happening. Code:
<html>
<head>
<title>Form Validator</title>
<script type="text/javascript">
//script here
function Validate()
{
var numbers = /^[0-9]+$/;
var emailRegex = /^[A-Za-z0-9._]*\#[A-Za-z]*\.[A-Za-z]{2,5}$/;
var fname = document.myform.FullName.value,
fmobile = document.myform.Mobile.value,
femail = document.myform.Email.value,
fpass1 = document.myform.pass1.value,
fpass2 = document.myform.pass2.value,
faddress = document.myform.Address.value;
if( fname == "" )
{
document.myform.FullName.focus() ;
document.getElementById("errorBox").innerHTML = "enter the name";
return false;
}
if (fmobile == "" )
{
document.myform.Mobile.focus();
document.getElementById("errorBox").innerHTML = "enter the Mobile Number";
return false;
}else if(!numbers.test(fmobile)){
document.myform.Mobile.focus();
document.getElementById("errorBox").innerHTML = "enter the valid Mobile number";
return false;
}
if (femail == "" )
{
document.form.Email.focus();
document.getElementById("errorBox").innerHTML = "enter the email";
return false;
}else if(!emailRegex.test(femail)){
document.form.Email.focus();
document.getElementById("errorBox").innerHTML = "enter the valid email";
return false;
}
if (fpass1 == "" )
{
document.myform.pass1.focus();
document.getElementById("errorBox").innerHTML = "enter the Password";
return false;
}else if(fpass1.length > 8){
document.myform.pass1.focus();
document.getElementById("errorBox").innerHTML = "Password must be greater than 8 length";
return false;
}
if (fpass2 == "" )
{
document.myform.pass2.focus();
document.getElementById("errorBox").innerHTML = "enter the Confirm Password";
return false;
}
if(fpass1 != fpass2){
document.myform.enterEmail.focus();
document.getElementById("errorBox").innerHTML = "Passwords are not matching, re-enter again";
return false;
}
if (faddress == "" )
{
document.myform.Address.focus();
document.getElementById("errorBox").innerHTML = "enter the Address";
return false;
}
if(fname != '' && fmobile != '' && femail != '' && fpass1 != '' && fpass2 != '' && faddress != '' ){
document.getElementById("errorBox").innerHTML = "form submitted successfully";
}
}
</script>// script ends here
</head>
<body>
<form action="" name="myform" method="post" onsubmit="return Validate()" style="text-align:-moz-center;">
// my html simple form start from here
<table cellspacing="2" cellpadding="2" border="0" >
<tr>
<td align="right">Full Name</td>
<td><input type="text" name="FullName"></td>
</tr>
<tr>
<td align="right">Mobile</td>
<td><input type="text" name="Mobile"></td>
</tr>
<tr>
<td align="right">Email</td>
<td><input type="text" name="Email"></td>
</tr>
<tr>
<td align="right">Password</td>
<td><input type="text" name="pass1"></td>
</tr>
<tr>
<td align="right">Confirm Password</td>
<td><input type="text" name="pass2"></td>
</tr>
<tr>
<td align="right">Address</td>
<td><textarea cols="20" rows="5" name="Address"></textarea></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" "> <div id="errorBox"></div></td>
</tr>
</table>
</form>
</body>
</html>

Missing a " on this row "enter the valid Mobile number";

Related

What is wrong with my form validation function?

I have a simple form that asks for Name, Email, Phone Number, Age and Income. When I hit submit, the validateForm function is supposed to check for errors and if there are any errors the textbox will be red and there will be a red error message display under the form. The function doesn't seem to be working at all and I'm not sure why.
This is my form and script. I tried setting the submit button to have an onclick event to call the function but that didn't work either.
<script>
function validateForm() {
if (document.forms.formValidation.Name.value == "") {
document.getElementById("error").style.display = "inline";
document.forms.formValidation.getElementById("name").style.backgroundColor = "red";
return false;
}
if (document.forms.formValidation.email.value == "") {
document.getElementById("error").style.display = "inline";
document.forms.formValidation.email.style.backgroundColor = "red";
}
var phoneNo = /^\d{10}$/;
if (document.forms.formValidation.number.value.match(phoneNo)) {
return true;
}
else {
document.getElementById("error").style.display = "inline";
document.forms.formValidation.number.style.backgroundColor = "red";
return false;
}
var emailVal = document.formValidation.email.value;
ampersandPos = emailVal.indexOf("#");
dotPos = emailVal.lastIndexOf(".");
if (amersandPos < 1 || (dotPos - amersandPos < 2)) {
alert("Please enter a valid email address.");
document.getElementById("error").style.display = "inline";
return false;
}
return true;
var len = age.length;
for (var i = 0; i < len; i++) {
if (document.forms.formValidation.age[i].checked)
{
return true;
}
else {
document.getElementById("error").style.display = "inline";
return false;
}
}
}
</script>
<form name="formValidation" onsubmit="return validateForm()">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">First and Last Name: </td>
<td align="left"><input type="text" id="name" name="Name" ></td>
</tr>
<tr>
<td align="right">Email: </td>
<td align="left"><input type="text" id="email" name="email" ></td>
</tr>
<tr>
<td align="right">Phone Number: </td>
<td align="left"><input type="text" name="number" /></td>
</tr>
<tr>
<td align="right">Age:</td>
<td class="rad"><input type="radio" name="age" value="minor">Under 18</td>
<td class="rad"><input type="radio" name="age" value="adult">18-64</td>
<td class="rad"><input type="radio" name="age" value="senior">65+</td>
</tr>
<tr>
<td align="right">Income:</td>
<td>
<select>
<option value="underFifty">Under $50,000</option>
<option value="fiftyToHundred">$50,000 - $100,000</option>
<option value="overHundred">Over $100,000</option>
</select>
</td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
<div id="error">
<p>Required fields are missing!</p>
</div>
You are missing a closing parenthesis on this line:
if (amersandPos < 1 || (dotPos - amersandPos < 2)
Also, this line is not valid:
document.formValidation.email.style.background-color = "red";
Because background-color is not a valid identifier name.
Here's a fiddle with these and the one issue in the comment fixed: https://jsfiddle.net/0zyv3g98/
You have mistakes in you js. you cannot use document.formValidation.name or something like that. the correct syntax is `document.forms.formValidation. Correction all your code and it will work.
if (document.forms.formValidation.Name.value == "") {
document.forms.formValidation.getElementById("error").style.display = "inline";
document.forms.formValidation.getElementById("name").style.backgroundColor = "red";
//return false;
}
if (document.forms.formValidation.email.value == "") {
document.forms.formValidation.getElementById("error").style.display = "inline";
document.forms.formValidation.email.style.backgroundColor = "red";
}
var emailVal = document.forms.formValidation.email.value;
ampersandPos = emailVal.indexOf("#");
dotPos = emailVal.lastIndexOf(".");
if (amersandPos < 1 || (dotPos - amersandPos < 2)
{
alert("Please enter a valid email address.");
document.forms.formValidation.getElementById("error").style.display = "inline";
return false;
}
return true;

registration form using Javascript and Php with MySql Database

I'm having problem with the registration for my website.
If I fill out the username field, and leave the others blank, no error-alerts are shown, it just saves the username to the database. There is supposed to be validation, like checking if the age is below 18, but I can't figure out where the error is.
register.php (javascript code & php code here):
<html>
<center><h1>Register Below</h1></center>
<body>
<br/>
<script>
function getText()
{
boolean sub = true;
var name = document.getElementById("t1").value;
if(name.length < 8 || name.length > 50)
{
sub=false;
alert("Invalid Username, must be 8 - 10 characters!")
document.getElementById("sample").innerHTML="*";
}
else
{
document.getElementById("sample").innerHTML = name;
}
var pass = document.getElementById("t2").value;
if(pass.length < 8 || pass.length > 50)
{
sub=false;
alert("Invalid Password, must be 8 - 10 characters!")
document.getElementById("sample2").innerHTML="*";
}
else
{
sub=true;
}
var rpass = document.getElementById("t3").value;
if(rpass!=pass)
{
sub=false;
alert("Password dont match!")
document.getElementById("sample3").innerHTML="*";
}
else
{
sub=true;
}
var fname = document.getElementById("t4").value;
if(fname.length<5||fname.length>15)
{
sub=false;
alert("Invalid firstname, must be 5 - 15 characters!")
}
else
{
document.getElementById("sample11").innerHTML = fname;
}
var lname = document.getElementById("t5").value;
if(lname.length<5||lname.length>15)
{
sub=false;
alert("Invalid lastname, must be 5 - 15 characters!")
}
else
{
document.getElementById("sample12").innerHTML = lname;
}
int age = parseInt(document.getElementById("t2").value);
if(age < 18)
{
sub=false;
alert("Minors not allowed.")
}
else
{
document.getElementById("sample4").innerHTML = age;
}
var email = document.getElementById("t7").value;
if(email.length < 8 || email.length > 50)
{
sub=false;
alert("Invalid Email, must be 8 - 50 characters!")
document.getElementById("sample2").innerHTML="*";
}
else
{
sub=true;
}
var lotnum = document.getElementById("t8a").value;
if(lotnum.length<3||lotnum.length>10)
{
sub=false;
alert("Location Invalid.")
}
else
{
document.getElementById("sample13").innerHTML = lotnum;
}
var sub = document.getElementById("t8b").value;
if(sub.length<5||sub.length>10)
{
sub=false;
alert("Location Invalid.")
}
else
{
document.getElementById("sample14").innerHTML = sub;
}
var city = document.getElementById("t8c").value;
if(city.length<5||city.length>10)
{
sub=false;
alert("Location Invalid.")
}
else
{
document.getElementById("sample15").innerHTML = city;
}
var country = document.getElementById("t9").value;
if(country.length<3||country.length>30)
{
sub=false;
alert("Location Invalid.")
}
else
{
document.getElementById("sample16").innerHTML = country;
}
int area = parseInt(document.getElementById("t10a").value);
if(area.length<3||area.length>8)
{
sub=false;
alert("Invalid Area Code, must be 3 - 8 digits!")
}
else
{
document.getElementById("sample16").innerHTML = area;
}
int telnum = parseInt(document.getElementById("t10b").value);
if(telnum.length<10||telnum.length>12)
{
sub=false;
alert("Invalid Number!")
}
else
{
document.getElementById("sample16").innerHTML = telnum;
}
if(sub==false)
{
return false;
}
}
</script>
<center>
<form method = "post" action = "insert.php" onSubmit="return getText()">
<table>
<tr>
<td>Username:</td>
<td colspan="3"><input name="t1" type="text" id="t1"><span id="sample">
</span><br></td>
</tr>
<tr>
<td>Password:</td>
<td colspan="3"><input name="t2" type="password" id="t2"><span id="sample2">
</span><br></td></td>
</tr>
<tr>
<td>Re-type Password:</td>
<td colspan="3"><input name="t3" type="password" id="t3"><span id="sample3">
</span><br></td></td>
</tr>
<tr>
<td>Firstname:</td>
<td colspan="3"><input name="t4" type="text" id="t4"><br></td>
</tr>
<tr>
<td>Lastname:</td>
<td colspan="3"><input name="t5" type="text" id="t5"><br></td>
</tr>
<tr>
<td>Age:</td>
<td colspan="3"><input name="t6" type="text" id="t6"><br></td>
</tr>
<tr>
<td>Email:</td>
<td colspan="3"><input name="t7" type="email" id="t7"><br></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="t8a" id="t8a"><br></td>
<td><input type="text" name="t8b" id="t8b"><br></td>
<td><input type="text" name="t8c" id="t8c"><br></td>
</tr>
<tr>
<td></td>
<td>Lot/Block#</td>
<td>Brgy/Subd</td>
<td>City/Municipality</td>
</tr>
<tr>
<td>Country:</td>
<td colspan="3"><input name="t9" type="text" id="t9"><br></td>
</tr>
<tr>
<td>Contact#:</td>
<td><input name="t10a" type="text" id="t10a"><br></td>
<td><input name="t10b" type="text" id="t10b"><br></td>
</tr>
<tr>
<td></td>
<td>Area Code</td>
<td>Number<td>
</tr>
</table>
<br><br>
<button type="submit" onClick="getText()">Submit</button><br><br>
<p id="log">
</p>
</form>
</center>
</body>
and the codes for my Database:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$db = mysql_connect("localhost","root","");
if($db){
mysql_select_db("user1",$db);
$username = $_POST['t1'];
$password = $_POST['t3'];
$firstname = $_POST['t4'];
$lastname = $_POST['t5'];
$age = $_POST['t6'];
$email = $_POST['t7'];
$lot = $_POST['t8a'];
$sub = $_POST['t8b'];
$city = $_POST['t8c'];
$country = $_POST['t9'];
$area = $_POST['t10a'];
$num = $_POST['t10b'];
if(mysql_query("insert into regform(username,password,firstname,lastname,age,email,lot,sub,city,country,area,num) values('$username','$password','$firstname','$lastname','$age','$email','$lot','$sub','$city','$country','$area','$num')"))
{
echo "Register Successful. Click <a href='index.html'> Here </a> to return";
}
else
{
echo "Registration Failed".mysql_error();
}
}
else{
echo "Cannot Connect in Database!";
}
?>
you are missing ; after each alert
try this code
<html>
<center><h1>Register Below</h1></center>
<body>
<br/>
<script>
function getText()
{
var sub = true ;
var name = document.getElementById("t1").value;
if(name.length < 8 || name.length > 50)
{
sub=false;
alert("Invalid Username, must be 8 - 10 characters!");
document.getElementById("sample").innerHTML="*";
}
else
{
document.getElementById("sample").innerHTML = name;
}
var pass = document.getElementById("t2").value;
if(pass.length < 8 || pass.length > 50)
{
sub=false;
alert("Invalid Password, must be 8 - 10 characters!");
document.getElementById("sample2").innerHTML="*";
}
else
{
sub=true;
}
var rpass = document.getElementById("t3").value;
if(rpass !== pass)
{
sub=false;
alert("Password dont match!");
document.getElementById("sample3").innerHTML="*";
}
else
{
sub=true;
}
var fname = document.getElementById("t4").value;
if(fname.length<5||fname.length>15)
{
sub=false;
alert("Invalid firstname, must be 5 - 15 characters!");
}
else
{
document.getElementById("sample11").innerHTML = fname;
}
var lname = document.getElementById("t5").value;
if(lname.length<5||lname.length>15)
{
sub=false;
alert("Invalid lastname, must be 5 - 15 characters!");
}
else
{
document.getElementById("sample12").innerHTML = lname;
}
var age = parseInt(document.getElementById("t2").value);
if(age < 18)
{
sub=false;
alert("Minors not allowed.");
}
else
{
document.getElementById("sample4").innerHTML = age;
}
var email = document.getElementById("t7").value;
if(email.length < 8 || email.length > 50)
{
sub=false;
alert("Invalid Email, must be 8 - 50 characters!");
document.getElementById("sample2").innerHTML="*";
}
else
{
sub=true;
}
var lotnum = document.getElementById("t8a").value;
if(lotnum.length<3||lotnum.length>10)
{
sub=false;
alert("Location Invalid.");
}
else
{
document.getElementById("sample13").innerHTML = lotnum;
}
var sub = document.getElementById("t8b").value;
if(sub.length<5||sub.length>10)
{
sub=false;
alert("Location Invalid.");
}
else
{
document.getElementById("sample14").innerHTML = sub;
}
var city = document.getElementById("t8c").value;
if(city.length<5||city.length>10)
{
sub=false;
alert("Location Invalid.");
}
else
{
document.getElementById("sample15").innerHTML = city;
}
var country = document.getElementById("t9").value;
if(country.length<3||country.length>30)
{
sub=false;
alert("Location Invalid.");
}
else
{
document.getElementById("sample16").innerHTML = country;
}
var area = parseInt(document.getElementById("t10a").value);
if(area.length<3||area.length>8)
{
sub=false;
alert("Invalid Area Code, must be 3 - 8 digits!")
}
else
{
document.getElementById("sample16").innerHTML = area;
}
var telnum = parseInt(document.getElementById("t10b").value);
if(telnum.length<10||telnum.length>12)
{
sub=false;
alert("Invalid Number!");
}
else
{
document.getElementById("sample16").innerHTML = telnum;
}
if(sub === false)
{
return false;
}
}
</script>
<center>
<form method = "post" action = "insert.php">
<table>
<tr>
<td>Username:</td>
<td colspan="3"><input name="t1" type="text" id="t1"><span id="sample">
</span><br></td>
</tr>
<tr>
<td>Password:</td>
<td colspan="3"><input name="t2" type="password" id="t2"><span id="sample2">
</span><br></td></td>
</tr>
<tr>
<td>Re-type Password:</td>
<td colspan="3"><input name="t3" type="password" id="t3"><span id="sample3">
</span><br></td></td>
</tr>
<tr>
<td>Firstname:</td>
<td colspan="3"><input name="t4" type="text" id="t4"><br></td>
</tr>
<tr>
<td>Lastname:</td>
<td colspan="3"><input name="t5" type="text" id="t5"><br></td>
</tr>
<tr>
<td>Age:</td>
<td colspan="3"><input name="t6" type="text" id="t6"><br></td>
</tr>
<tr>
<td>Email:</td>
<td colspan="3"><input name="t7" type="email" id="t7"><br></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="t8a" id="t8a"><br></td>
<td><input type="text" name="t8b" id="t8b"><br></td>
<td><input type="text" name="t8c" id="t8c"><br></td>
</tr>
<tr>
<td></td>
<td>Lot/Block#</td>
<td>Brgy/Subd</td>
<td>City/Municipality</td>
</tr>
<tr>
<td>Country:</td>
<td colspan="3"><input name="t9" type="text" id="t9"><br></td>
</tr>
<tr>
<td>Contact#:</td>
<td><input name="t10a" type="text" id="t10a"><br></td>
<td><input name="t10b" type="text" id="t10b"><br></td>
</tr>
<tr>
<td></td>
<td>Area Code</td>
<td>Number<td>
</tr>
</table>
<br><br>
<button type="submit" onClick="getText()">Submit</button><br><br>
<p id="log">
</p>
</form>
</center>
</body>

Form validation without error on IE

I have a html code saved as a php, the form validation works in google chrome but not in IE. In IE after I hit the submit button, the page automatically goes to process form regardless of errors.
This is my code:
<!DOCTYPE html>
<html>
<head>
<title>Week 8 Lab - JavaScript DOM and Arrays</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validateForm() {
var errors = 0;
var fName = document.forms["orderForm"].firstName.value;//first name validation
if (fName == null || fName == "")
{
document.getElementById('firstNameError').innerHTML = "Please enter a first name.";
errors++;
} else {
document.getElementById('firstNameError').innerHTML = "";
}
//var lName = document.forms["orderForm"].lastName.value;//last name validation
if (lName == null || lName == "")
{
document.getElementById('lastNameError').innerHTML = "Please enter a last name.";
errors++;
} else {
document.getElementById('lastNameError').innerHTML = "";
}
//var address = document.forms["orderForm"].address.value;//address validation
if (address == null || address == "")
{
document.getElementById('addressError').innerHTML = "Please enter an address.";
errors++;
} else {
document.getElementById('addressError').innerHTML = "";
}
//var city = document.forms["orderForm"].city.value;//city validation
if (city == null || city == "")
{
document.getElementById('cityError').innerHTML = "Please enter a city.";
errors++;
} else {
document.getElementById('cityError').innerHTML = "";
}
//var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if (pCodeCheck)
{
document.getElementById('postalCoderror').innerHTML = "";
}
else
{
document.getElementById('postalCoderror').innerHTML = "Please enter a valid postal code.";
errors++;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if (itemQTY < 0)
{
document.getElementById('qtyError').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError').innerHTML = "";
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if (itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError2').innerHTML = "";
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if (itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError3').innerHTML = "";
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if (wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML = "You must order atleast one item.";
errors++;
} else {
document.getElementById('itemQTY').innerHTML = "";
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3);
alert('Your total is: $' + total4 + '.00');
return errors;
}
function startValidate() {
var errors = validateForm();
if (errors == 0) {
document.forms['orderForm'].submit();
} else {
return false;
}
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" action="processForm.html" onsubmit="return startValidate()">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Quebec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit Order">
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
When you look at the console in IE’s developer tools (F12), you will see that there is an error message about undeclared variable lName. This causes the error checking to be aborted.
You have several lines like
//var lName = document.forms["orderForm"].lastName.value;//last name validation
Since // starts a comment in JavaScript, the line has no effect. The variable lName is not declared or defined elsewhere either.
So you need to remove those // comment starters. Note that the code does not work in Chrome either; you may have tested a different version in Chrome, or misinterpreted some behavior.
In the console, you can also see a message for line 237 about “unexpected identifier”. It is actually a serious HTML markup error; IE reports some of such errors, in a strange way. The error is that a tr element has an input element as child, which is forbidden in HTML syntax. This is why the Submit Order and Reset Form appear on top of each other and not on the same row as intended. (For usability, the Reset Form button should be removed, but I digress.)

how to show an alert after validation but before submission

I have all of my validation code figured out but I'm not quite sure on how to code an alert to pop up before the form is submitted but after the validation is complete.
<!DOCTYPE html>
<html>
<head>
<title>Week 8 Lab - JavaScript DOM and Arrays</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validate()
{
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if(lName==null || lName=="")
{
document.getElementById('lastNameError').innerHTML= "Please enter a last name.";
return false;
}
var address = document.forms["orderForm"].address.value;//address validation
if(address==null || address=="")
{
document.getElementById('addressError').innerHTML= "Please enter an address.";
return false;
}
var city = document.forms["orderForm"].city.value;//city validation
if(city==null || city=="")
{
document.getElementById('cityError').innerHTML= "Please enter a city.";
return false;
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if(postalCode.value.match(pCodeCheck))
{
//do nothing
return true;
}
else
{
document.getElementById('postalCoderror').innerHTML= "Please enter a valid postal code.";
return false;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if(itemQTY < 0)
{
document.getElementById('qtyError').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if(itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if(itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML= "You cannot enter a negative number.";
return false;
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if(wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML= "You must order atleast one item.";
return false;
}
/*
// trying to send alert with the order total.
// not sure how to call it after the validation is done.
var total1;
var total2;
var total3:
var total4;
if(document.getElementById('widget1qty').value == 0)
{
total1 = 0;
}
else(document.getElementById('widget1qty').value != 0)
{
total1 = document.getElementById('widget1qty').value * 5;
}
if(document.getElementById('widget2qty').value == 0)
{
total2 = 0;
}
else(document.getElementById('widget2qty').value != 0)
{
total2 = document.getElementById('widget2qty').value * 15;
}
if(document.getElementById('widget3qty').value == 0)
{
total3 = 0;
}
else(document.getElementById('widget3qty').value != 0)
{
total3 = document.getElementById('widget3qty').value * 25;
}
total4 = (total1 + total2 + total3)
alert('Your total is: $' + total4 + '.00');
*/
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" onsubmit="validate();" action="processForm.html">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Québec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr></tr><tr></tr><tr></tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<td><input type="submit" name="btnSubmit" id="btnSubmit" onclick="return validate();" value="Submit Order"></td>
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
I just don't know how to code it to pop up after the validation is complete.
In your form, you could put anid = "myForm"and then do this in javascript:
function validateForm() {
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if(lName==null || lName=="")
{
document.getElementById('lastNameError').innerHTML= "Please enter a last name.";
return false;
}
var address = document.forms["orderForm"].address.value;//address validation
if(address==null || address=="")
{
document.getElementById('addressError').innerHTML= "Please enter an address.";
return false;
}
var city = document.forms["orderForm"].city.value;//city validation
if(city==null || city=="")
{
document.getElementById('cityError').innerHTML= "Please enter a city.";
return false;
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if(postalCode.value.match(pCodeCheck))
{
//do nothing
return true;
}
else
{
document.getElementById('postalCoderror').innerHTML= "Please enter a valid postal code.";
return false;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if(itemQTY < 0)
{
document.getElementById('qtyError').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if(itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if(itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML= "You cannot enter a negative number.";
return false;
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if(wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML= "You must order atleast one item.";
return false;
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3)
alert('Your total is: $' + total4 + '.00');
return;
}
function startValidate(){
validateForm();
document.forms['orderForm'].submit();
}
Edit:
Just add all the other info in the validateForm() function.
I did't seen it because I started my edit before you added the HTML and the other JS.
According to War10ck's post you should change this :
<input type="submit" name="btnSubmit" id="btnSubmit" onsubmit="startValidate()" value="Submit Order">
You can make another function called FireOnSubmit and do something like this:
`
function FireOnSubmit(){
if(validate()==true) alert(""form validated..is being redirected")
else {
alert("invalid form data");
return false;
}
}
`
You can put FireOnSubmit on the onsubmit of the form instead of the validate function.
Also, you will need to return true or false from your validate function.
Instead of all that JavaScript, this should work just as well.
The submit button cannot be clicked until all fields you pick have been filled.
Then a alert pops up with your message.
This Goes In The Head Section
<script>
function checkform()
{
var f = document.forms["testform"].elements;
var cansubmit=true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length==0) cansubmit=false;
}
if (cansubmit)
{
document
.getElementById('submit'
).disabled=false;
}
}
</script>
Here Is The Form. The Submit Button Is Disabled Until All Fields Are Filled.
<form name="testform">
<input type="text" onKeyup="checkform()" placeholder="First Name"required/><br>
<input type="text" onKeyup="checkform()" placeholder="Last Name" required/><br>
<input id="submit" type="submit" disabled="disabled" value="Submit" onclick="alert('Your Alert Here...')"/>
</form>

asp and javascript message alert doesn't work

here's my code
<%
if request.form("Add") = " Add " then
if request.form("txtdistributor") = "" or request.form("sinumber") = "" or request.form("tstdate") = "" or request.form("drnumber") = "" or request.form("drdate") = "" or request.form("receivedby") = "" then
response.redirect("salesinvoice.asp?userloggedin=" &request.querystring("userloggedin") &"&dist=" &request.QueryString("dist") )
end if
SQLString = "INSERT INTO salesinvoice (distributor,sidate,sinumber) VALUES ('" & Request.form("txtdistributor") & "','" & Request.Form("tstdate") & "','" & Request.Form("sinumber") &"') "
set DBConn = Server.CreateObject("ADODB.Connection")
DBConn.Open Application("dals_ConnectionString")
DBConn.Execute(SQLString)
DBConn.Close
set DBConn = Server.CreateObject("ADODB.Connection")
DBConn.Open Application("dals_ConnectionString")
SQLString = "INSERT INTO Delivery_Receipt (Date_Purchase, Receipt_no, Distributor, Received_by, Entry_Date,sinumber) VALUES"
SQLString = SQLString & "('" & Request.Form("drdate") & "','" & Request.Form("drnumber") & "', '" & Request.Form("txtdistributor")& "','" & Request.Form("receivedby") & "','" & now() & "','" & request.Form("sinumber") & "')"
DBConn.Execute(SQLString)
DBConn.Close
response.Redirect("salesinvoice.asp?userloggedin=" &request.QueryString("userloggedin") &"&dist=" &request.QueryString("dist"))
end if
%>
<!-- Javascript -->
<script type="text/javascript">
function validateform()
{
if (document.frm.txtdistributor.value == '')
{
alert('Please input distributor');
document.frm.txtdistributor.focus();
return false;
}
if (document.frm.txtdistributor.value == '')
{
alert('Please input distributor');
document.frm.txtdistributor.focus();
return false;
}
if (document.frm.sinumber.value == '')
{
alert('Please input sales invoice number');
document.frm.sinumber.focus();
return false;
}
if (document.frm.tstdate.value == '')
{
alert('Please input sales invoice date');
document.frm.tstdate.focus();
return false;
}
if (document.frm.drnumber.value == '')
{
alert('Please input Delivery Receipt Number');
document.frm.drnumber.focus();
return false;
}
if (document.frm.drdate.value == '')
{
alert('Please input Delivery Receipt');
document.frm.drdate.focus();
return false;
}
if (document.frm.receivedby.value == '')
{
alert('Please input requestor');
document.frm.receivedby.focus();
return false;
}
return true;
}
</script>
<html>
<head>
<title>Sales Invoice</title>
</head>
<body>
<!--#include file="header.asp"-->
<form name="frm" id="frm" action="salesinvoice.asp?userloggedin=<%=request.QueryString("userloggedin")%>&dist=<%=request.QueryString("dist")%>" method="post" onSubmit="return validateform();">
<link href="css/calendar.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="calendar_date_picker.js"></script>
<script type="text/javascript">
var cdp1 = new CalendarDatePicker();
var props = {
debug : true,
excludeDays : [6,0,1],
excludeDates : ['20081225','20081226','20091225','20091226'],
minimumFutureDate : 5,
formatDate : '%m-%d-%y'
};
var cdp2 = new CalendarDatePicker(props);
props.formatDate = '%d-%m-%y';
var cdp3 = new CalendarDatePicker(props);
cdp3.endYear = cdp3.startYear + 1;
</script>
<table width="900" align="center">
<tr>
<td width="200">Distributor</td>
<td>
<%if request.querystring("dist") <> "yes" then%>
<select name="txtdistributor" style="width:260;">
<option value="">- Select -</option>
<%
strsql = "select Distinct(Distributor) from salesinvoice"
set rsdist = server.createobject("adodb.recordset")
rsdist.open strsql,application("dals_connectionstring")
while not rsdist.eof
%>
<option value="<%=rsdist("distributor")%>"><%=rsdist("distributor")%></option>
<%
rsdist.movenext
wend
rsdist.close
set rsdist = nothing
%>
</select> Add New Distributor
<%end if%>
<%if request.querystring("dist") <> "no" then%>
<input type="text" size="38" name="txtdistributor" id="txtdistributor"> [ - ]
<%end if%>
</td>
</tr>
<tr>
<td>SI Number</td>
<td><input type="text" name="sinumber" id="sinumber"></td>
</tr>
<tr>
<td>SI Date</td>
<td><input type="text" name="tstdate" id="txtdate" readonly> <img src="images/calendar.png" border="0" align="absmiddle" style="cursor:hand;" title="Calendar"></td>
</tr>
<tr>
<td>DR Number</td>
<td><input type="text" name="drnumber" id="drnumber"></td>
</tr>
<tr>
<td>DR date</td>
<td><input type="text" name="drdate" id="drdate" readonly> <img src="images/calendar.png" border="0" align="absmiddle" style="cursor:hand;" title="Calendar"></td>
</tr>
<tr>
<td>Received by</td>
<td>
<!--<input type="text" name="receivedby" id="receivedby">-->
<select name="receivedby" id="receivedby">
<option value="">- Select -</option>
<%
strsql = "select first_name,last_name from sysadusers"
set rsname = server.CreateObject("adodb.recordset")
rsname.open strsql,application("dals_connectionstring")
while not rsname.eof
%>
<option value="<%=rsname("first_name")%>, <%=rsname("last_name")%>"><%=rsname("first_name")%>, <%=rsname("last_name")%></option>
<%
rsname.movenext
wend
rsname.close
%>
</select>
You might have runtime error in the validation function, for example when the form does not contain the txtdistributor drop down.
For the sake of debugging, change the function to this only:
function validateform() {
alert("validation started");
var oDDL = document.frm.txtdistributor;
if (oDDL) {
if (oDDL.value == '') {
alert('Please input distributor');
oDDL.focus();
}
} else {
alert("form does not contain txtdistributor");
}
alert("validation ended");
return false;
}
If this works, apply the same logic for the rest of the fields and remove the debug messages.

Categories

Resources