form validation not working along with form action - javascript

I have a registration form which SHOULD check the inputting data according to each function i have created(inside validation.js file) and after everything is ok then it should return all the data to the .php file which will save inthe phpmyadmin database.
However it is not working
Test1: validation is working (alone not included the action=.php)
Test2: without validation the data is storing in the database(phpmyadmin)
Test3: with validation and with action=.php) its not working the validation part
Please help me.
function formValidation()
{
var id = document.registration.nic;
var registerno = document.registration.regno;
var name = document.registration.pname;
var paddress = document.registration.address;
var maritial = document.registration.mars;
var religion = document.registration.rel;
var addname = document.registration.fhn;
var pcity = document.registration.city;
var telephone = document.registration.tel;
var age = document.registration.ag;
var gender = document.registration.gen;
if(ValidateNIC(id)) //done
{
if(allLettername(name)) //done
{
if(allnumericreg(registerno))
{
if(alphanumericpaddress(paddress)) //done
{
if(maritialselect(maritial)) //done
{
if(religionselect(religion)) //done
{
if(allLetteraddname(addname)) //done
{
if(alphanumericpcity(pcity)) //done
{
if(allnumerictel(telephone)) //done
{
if(allnumericage(age)) //done
{
if(genderselect(gender)) //done
{
}
}
}
}
}
}
}
}
}
}
}
return false;
}
function allLettername(name)
{
var letters = /^[A-Za-z ]+$/;
if(name.value.match(letters))
{
return true;
}
else
{
alert('Patient Name must have alphabet characters only');
return false;
}
}
function allLetteraddname(addname)
{
var letters = /^[A-Za-z ]+$/;
if(addname.value.match(letters))
{
return true;
}
else
{
alert('Father or Husband"s Name must have alphabet characters only');
return false;
}
}
function maritialselect(maritial)
{
if(maritial.value == "Default")
{
alert("Select your Maritial Status from the list");
return false;
}
else
{
return true;
}
}
function ValidateNIC(id)
{
var letters = /^[0-9a-zA-Z ]+$/;
if ((id.value.length == 10) && id.value.match(letters))
{
return true;
}
else
{
alert("NIC must contain alphanumeric characters only and must be 10 charators long!");
id.focus();
return false;
}
}
function alphanumericpaddress(paddress)
{
var letters = /^[0-9a-zA-Z ]+$/;
if(paddress.value.match(letters))
{
return true;
}
else
{
alert('Patient address must have alphanumeric characters only');
paddress.focus();
return false;
}
}
function alphanumericpcity(pcity)
{
var letters = /^[0-9a-zA-Z ]+$/;
if(pcity.value.match(letters))
{
return true;
}
else
{
alert('User City must have alphanumeric characters only');
pcity.focus();
return false;
}
}
function religionselect(religion)
{
if(religion.value == "Default")
{
alert("Select your Religion from the list");
return false;
}
else
{
return true;
}
}
function allnumericreg(registerno)
{
var numbers = /^[0-9]+$/;
if(registerno.value.match(numbers))
{
return true;
}
else
{
alert("Register No Must have numeric characters only");
return false;
}
}
function allnumerictel(telephone)
{
var numbers = /^[0-9]+$/;
if((telephone.value.length == 10) && telephone.value.match(numbers))
{
return true;
}
else
{
alert("Telephone Number must have numeric characters only and Length should 10 charators long! ");
return false;
}
}
function allnumericage(age)
{
var numbers = /^[0-9]+$/;
if(age.value.match(numbers))
{
return true;
}
else
{
alert("Age must have numeric characters only");
return false;
}
}
function genderselect(gender)
{
if(gender.value == "Default")
{
alert("Select your Gender from the list");
return false;
}
else
{
alert('Registration Form Successfully Submitted');
window.location.reload()
return true;
}
}
<?php
$con= mysqli_connect ("localhost","root","","hmsjason");
if (mysqli_connect_error()){
echo"Failed to Connect";
}
$sql="INSERT INTO patient(P_NIC,Reg_No,Full_Name,Address,Maritial_Sts,Religion,DOB,H_F_Name,City,Contact,Age,Gender,Room_No)VALUES('$_POST[nic]','$_POST[regno]','$_POST[pname]','$_POST[address]','$_POST[mars]','$_POST[rel]','$_POST[dob]','$_POST[fhn]','$_POST[city]','$_POST[tel]','$_POST[ag]','$_POST[gen]','$_POST[room]')";
if(!mysqli_query($con,$sql)){
die("Error".mysqli_error($con));
}
mysqli_close($con);
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
header("location:reception.html");
?>
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="style1.css">
<script src="regvalidation.js"></script>
</head>
<body>
<br><br><br>
<table background="Images/formbg1.jpg" border="2" align="center" width ="825" height="820" >
<th align=center valign=center>
<form action="patientdetails.php" method="POST"/>
<!--form name='registration' onSubmit="return formValidation()"/>-->
<div class="textcenter1">
<h2>Patient Registration Form</h2>
</div>
<br><br>
<table border="0"; align="center" width ="655" height="550" >
<tr>
<td>
NATIONAL ID :</td><td><input type="text" name="nic" size="40" />
</td>
</tr>
<tr>
<td>
<b>
REGISTRATION NUMBER :</td><td><input type="text" name="regno" size="40" />
</td>
</tr>
<tr>
<td>
PATIENT NAME :</td><td><input type="text" name="pname" size="40" />
</td>
<tr>
<td>
PATIENT ADDRESS :</td><td><input type="text" name="address" size="40" />
</td>
</tr>
<tr>
<td>
Maritial Status: :</td>
<td>
<select name="mars">
<option selected="" value="Default">(Please select your Status)</option>
<option value="Maried">Married</option>
<option value="Unmarried">UnMarried</option>
</select>
</td>
</tr>
<tr>
<td>
RELIGION :</td>
<td>
<select name="rel">
<option selected="" value="Default">(Please select your Religion)</option>
<option value="Buddhist">Buddhist</option>
<option value="Catholic">Catholic</option>
<option value="Christian">Christian</option>
<option value="Hindu">Hindu</option>
<option value="Muslim">Muslim</option>
<option value="Others">Others</option>
</select>
</td>
</tr>
<tr>
<td>
Date of Birth: </td><td><input type="date" name="dob">
<td>
</tr>
<tr>
<td>
FATHER'S NAME/HUSBAND'S NAME :</td><td><input type="text" name="fhn" size="40" />
</td>
</tr>
<tr>
<td>
CITY :</td><td><input type="text" name="city" size="40" />
</td>
</tr>
<tr>
<td>
TELEPHONE NUMBER/MOBILE NUMBER :</td><td><input type="text" name="tel" size="40" />
</td>
</tr>
<tr>
<td>
AGE :</td><td><input type="text" name="ag" size="40" />
</td>
</tr>
<tr>
<td>
Gender :</td>
<td>
<select name="gen">
<option selected="" value="Default">(Please select your Gender)</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr>
<td>
Room: </td><td><input type="text" name="room">
<td>
</tr>
</b>
<tr>
<td></td>
<td>
<input align="left" type="image" src="Images/submit.png" alt="Submit" name="submit" value="Submit" width="115" height="57"/>
</form>
<!--if submit button and reset button in same <form> will perform the formvalidation which leds the reset buttton also work as a submit button(wont reset anyting)-->
<form><input align="center" type="image" src="Images/reset.png" alt="Reset" name="reset" value="reset" width="115" height="57"/>
</td>
</tr>
</form>
</table>
</th>
</table>
<br><br>
</body>
</html>

It appears your validation method always returns false. If the code called by onSubmit returns false, the action will not be executed. The same is true for onclick and other event functions.
Once you've evaluated all the conditions to be valid, you should return true to tell the form that it can take over and do its thing.

Related

Why the form submission is possible even after form fields are empty?

Here is the HTML
<form action="../phpFiles/reportCalorie.php" method="post"
onsubmit="return calculateCalorie()" name="bmiform">
<select name="activity" >
<option value="">Select any activity</option>
<option value="1">baseball</option>
<option value="2">basketball</option>
<option value="3">jogging</option>
<option value="4">walking</option>
<option value="5">Cycling</option>
<option value="6">Running</option>
<option value="7">Swimming</option>
<option value="8">Handball</option>
<option value="9">Cricket</option>
<option value="10">Football</option>
</select>
</td>
</tr>
<tr>
<td><h4>How many minutes?</h4></td>
<td>
<input type="number" name="minutes" size="5px"/>
minutes
</td>
</tr>
<tr>
<td><h4>Enter your weight</h4></td>
<td>
<input type="text" name="weight" size="5px"/>
KG
</td>
</tr>
<tr>
<td><h4>Enter your Age</h4></td>
<td>
<input type="text" name="age" size="5px"/>
Years
</td>
</tr>
<tr>
<td><h4>Enter your height</h4></td>
<td>
<input type="text" name="feet" size="5px"/>
FEET
<input type="text" name="inches" size="5px"/>
inches
</td>
</tr>
<tr>
<td colspan="2">
<input class="button1" type="submit" name="calculate"
value="Calculate" title="calculate" onclick="calculateCalorie()"/>
<br/><br/>
</form>
Here is the Javascript
<script type="text/javascript">
function calculateCalorie()
{
if(validate())
{
var minutes=+document.bmiform.minutes.value;
var weight=+document.bmiform.weight.value;
return true
}
else
{
return false;
}
}
function validate()
{
var age = document.bmiform.age.value;
var feet = document.bmiform.feet.value;
var inches = document.bmiform.inches.value;
var weight = document.bmiform.weight.value;
var minutes= document.bmiform.minutes.value;
if(age =="" || feet=="" || inches=="" || weight=="" || minutes=="")
{
alert("Your fields are empty");
return false
}
else if(isNaN(age) || isNaN(feet) || isNaN(inches) ||
isNaN(weight) isNaN(minutes) )
{
alert("Please enter valid input")
return false;
}
else{
return true;
}
}
</script>
I do not understand that even i left the field empty why it accepting the form and direct me to other page. please if anything is wrong just let me know? I would greatly appreciated any help.
There are 2 minor issues with the code, one being the cause of the error. The first is that there's a syntax error in the isNaN check which should be changed to isNaN(weight) || isNaN(minutes).
Second, the <input ... has an onclick listener in addition to your form's onsubmit listener, which runs the validation twice and could cause problems later on.
(Note that I changed the alert into console.log, so the snippet would work)
function calculateCalorie()
{
if(validate())
{
var minutes=+document.bmiform.minutes.value;
var weight=+document.bmiform.weight.value;
console.log('submitting');
return true
}
else
{
return false;
}
}
function validate()
{
var age = document.bmiform.age.value;
var feet = document.bmiform.feet.value;
var inches = document.bmiform.inches.value;
var weight = document.bmiform.weight.value;
var minutes= document.bmiform.minutes.value;
if(age =="" || feet=="" || inches=="" || weight=="" || minutes=="")
{
console.log("Your fields are empty");
return false;
}
else if(isNaN(age) || isNaN(feet) || isNaN(inches) ||
isNaN(weight) || isNaN(minutes) )
{
console.log("Please enter valid input")
return false;
}
else{
return true;
}
}
<form action="../phpFiles/reportCalorie.php" method="post"
onsubmit="return calculateCalorie()" name="bmiform">
<select name="activity" >
<option value="">Select any activity</option>
<option value="1">baseball</option>
<option value="2">basketball</option>
<option value="3">jogging</option>
<option value="4">walking</option>
<option value="5">Cycling</option>
<option value="6">Running</option>
<option value="7">Swimming</option>
<option value="8">Handball</option>
<option value="9">Cricket</option>
<option value="10">Football</option>
</select>
</td>
</tr>
<tr>
<td><h4>How many minutes?</h4></td>
<td>
<input type="number" name="minutes" size="5px"/>
minutes
</td>
</tr>
<tr>
<td><h4>Enter your weight</h4></td>
<td>
<input type="text" name="weight" size="5px"/>
KG
</td>
</tr>
<tr>
<td><h4>Enter your Age</h4></td>
<td>
<input type="text" name="age" size="5px"/>
Years
</td>
</tr>
<tr>
<td><h4>Enter your height</h4></td>
<td>
<input type="text" name="feet" size="5px"/>
FEET
<input type="text" name="inches" size="5px"/>
inches
</td>
</tr>
<tr>
<td colspan="2">
<input class="button1" type="submit" name="calculate"
value="Calculate" title="calculate" />
<br/><br/>
</form>
else if(isNaN(age) || isNaN(feet) || isNaN(inches) ||
isNaN(weight) isNaN(minutes) )
You`ve missed "||" operator here. It triggers a syntax error, which fails further javascript execution.
You have an error in your code your missing an || operator
else if(isNaN(age) || isNaN(feet) || isNaN(inches) ||
isNaN(weight) || isNaN(minutes) )
{
alert("Please enter valid input")
return false;
}
You should also call preventDefault to prevent the default form.
function customSubmitFunction(evt) {
evt.preventDefault();
someBug();
return false;
}
In this case, even with the bug the form won't submit!

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.)

Javascript submit function returns Object is not a function error

Am using this function for the form submission just after one last check of 2 fields. But when submitting the form using javascript it returns the Object is not a function error. Didnt pasted the entire code of this page. pasted the required fields for this function. Any helps appreciated
<script type="text/javascript">
function validamt(strval){
var letters = /^[0-9]+(\.[0-9]{1,2})?$/;
if (letters.test(strval)) {
return true;
} else {
return false;
}
}
function validno(strval){
var letters = /^\d+$/;
if (letters.test(strval)) {
return true;
} else {
return false;
}
}
function finalcheck(){
var discount=$("#discount").val();
var stax=$("#stax").val();
var err=0;
if(discount!="In Rupees only" || stax!="(%)"){
if(!validno(stax)){err=1; alert('Invalid Service Tax');$("#stax").focus();}
if(!validamt(discount)){err=1;alert('Invalid Discount Amount');$("#discount").focus();}
}
alert(err);
if(err==0){
try{
document.getElementById('billsetupprocess').action="storebilling.php";
document.getElementById('billsetupprocess').submit();
}
catch(e){
alert(e);
}
}
}
</script>
<form name="billsetupprocess" id="billsetupprocess" method="post" action="storebilling.php" enctype="multipart/form-data" >
<table>
<tr>
<td>Discount</td>
<td><input name="discount" type="text" class="txtclass" id="discount" value="<?php if($discount!=""){echo $discount;} else {echo("In Rupees only");}?>" autocomplete="off" onfocus="Javascript:if(this.value=='In Rupees only'){this.style.color='rgb(193,193,193)';this.value='';}" onblur="Javascript:if(this.value==''){this.style.color='rgb(193,193,193)';this.value='In Rupees only';}" onkeyup="Javascript:if(this.value!=''){this.style.color='rgb(0,133,189)';}"/></td>
<td></td>
<td> </td>
</tr>
<tr>
<td>servicetax</td>
<td><input name="stax" type="text" class="txtclass" id="stax" value="<?php if($discount!=""){echo $servicetax;}else {echo("(%)");}?>" autocomplete="off" onfocus="Javascript:if(this.value=='(%)'){this.style.color='rgb(193,193,193)';this.value='';}" onblur="Javascript:if(this.value==''){this.style.color='rgb(193,193,193)';this.value='(%)';}" onkeyup="Javascript:if(this.value!=''){this.style.color='rgb(0,133,189)';}"/>
</td>
<td></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td><input name="submit" id="submit" type="button" value="Save Setup" onclick="finalcheck()" class="btnclass" /></td>
<td> </td>
<td> </td>
</tr>
</table>

Javascript Form Validation won't validate

I'm having some issues validating my form. When I click to validate, it doesn't do anything other than refocus the page the first time, and the second time the page continues to the server. I've been looking for a few hours trying to find what the problem is, but I just can't see it.
Here is my Javascript code:
function formValidation() {
var uname = document.GetElementByName("UserName");
var uname = document.joinform.UserName;
var password = document.joinform.Password;
var fname = document.joinform.firstname;
var mname = document.joinform.middlename;
var lname = document.joinform.lastname;
var unationality = document.joinform.nationality;
var ulcontact = document.joinform.lpreferredcontact;
var umcontact = document.joinform.mpreferredcontact;
var uecontact = document.joinform.epreferredcontact;
var ulandline = document.joinform.dayphone;
var umobile = document.joinform.mobphone;
var uemail = document.joinform.email;
var uadd1 = document.joinform.address1;
var uadd2 = document.joinform.address2;
var upostcode = document.joinform.postcode;
var city = document.joinform.city;
var state = document.joinform.state;
var occupation = document.joinform.occupation;
var hobbies = document.joinform.hobbies;
var interest = document.joinform.interest;
if (username_validation(uname, 20, 20)) {
} else {
return false;
}
{
if (username_validation(uname, 20, 20)) {
if (password_validation(password, 20, 20)) {
if (allLetter(fname)) {
if (allLetter(mname)) {
}
}
}
}
return false;
}
if(username_validation(uname,20,20)) {
if(passid_validation(password,20,20)) {
if(allLetter(fname)) {
if(allLetter(mname)) {
if(allLetter(lname)) {
if(allLetter(unationality)) {
if(validcontact(ulcontact,umcontact,uecontact)) {
if(allnumeric(ulandline)) {
if(allnumeric(umobile)) {
if(ValidateEmail(uemail)) {
if(alphanumeric(uadd1)) {
if(alphanumeric(uadd2)) {
if(allnumeric(upostcode)) {
if(allLetter(city)) {
if(stateselect(state)) {
if(allLetter(occupation)) {
if(allLetter(hobbies)) {
if(interestselect(interest)) {
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
function username_validation(uname,mx,my)
{
var uname_len = uname.value.length;
if (uname_len >= my || uname_len < mx)
{
alert("User name length should be between "+mx+" to "+my);
uname.focus();
return false;
}
return true;
}
function password_validation(password,mx,my)
{
var password_len = password.value.length;
if (password_len >= my || password_len < mx)
{
alert("Password length should be between "+mx+" to "+my);
password.focus();
return false;
}
return true;
}
function allLetter(fname)
{
var letters = /^[A-Za-z]+$/;
if(fname.value.match(letters))
{
return true;
}
else
{
alert('First name must have alphabet characters only');
fname.focus();
return false;
}
}
function allLetter(mname)
{
var letters = /^[A-Za-z]+$/;
if(mname.value.match(letters))
{
return true;
}
else
{
alert('Middle name must have alphabet characters only');
mname.focus();
return false;
}
}
function allLetter(lname)
{
var letters = /^[A-Za-z]+$/;
if(lname.value.match(letters))
{
return true;
}
else
{
alert('Last name must have alphabet characters only');
lname.focus();
return false;
}
}
function allLetter(unationality)
{
var letters = /^[A-Za-z]+$/;
if(unationality.value.match(letters))
{
return true;
}
else
{
alert('Nationality must have alphabet characters only');
unationality.focus();
return false;
}
}
function validcontact(ulcontact,umcontact,uecontact)
{
x=0;
if(ulcontact.checked)
{
x++;
}
if(umcontact.checked)
{
x++;
} if(uecontact.checked)
{
x++;
}
if(x==0)
{
alert('Select the preferred Contact method');
ulcontact.focus();
return false;
}
function allnumeric(ulandline)
{
var numbers = /^[0-9]+$/;
if(ulandline.value.match(numbers))
{
return true;
}
else
{
alert('landline number must have numeric characters only');
ulandline.focus();
return false;
}
}
function allnumeric(umobile)
{
var numbers = /^[0-9]+$/;
if(umobile.value.match(numbers))
{
return true;
}
else
{
alert('mobile number must have numeric characters only');
umobile.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
}
function alphanumeric(uadd1)
{
var letters = /^[0-9a-zA-Z]+$/;
if(uadd1.value.match(letters))
{
return true;
}
else
{
alert('User address must have alphanumeric characters only');
uadd1.focus();
return false;
}
}
function alphanumeric(uadd2)
{
var letters = /^[0-9a-zA-Z]+$/;
if(uadd2.value.match(letters))
{
return true;
}
else
{
alert('User address must have alphanumeric characters only');
uadd2.focus();
return false;
}
}
function allnumeric(postcode)
{
var numbers = /^[0-9]+$/;
if(postcode.value.match(numbers))
{
return true;
}
else
{
alert('postcode must have numeric characters only');
postcode.focus();
return false;
}
}
function allLetter(city)
{
var letters = /^[A-Za-z]+$/;
if(city.value.match(letters))
{
return true;
}
else
{
alert('City must have alphabet characters only');
city.focus();
return false;
}
}
function stateselect(state)
{
if(state.value == "Default")
{
alert('Select your state from the list');
state.focus();
return false;
}
else
{
return true;
}
}
function allLetter(occupation)
{
var letters = /^[A-Za-z]+$/;
if(occupation.value.match(letters))
{
return true;
}
else
{
alert('Occupation must have alphabet characters only');
occupation.focus();
return false;
}
}
function allLetter(hobbies)
{
var letters = /^[A-Za-z]+$/;
if(hobbies.value.match(letters))
{
return true;
}
else
{
alert('Hobbies must have alphabet characters only');
hobbies.focus();
return false;
}
}
function interestselect(interest) {
if (interest.value == "Default") {
alert('Select your interest from the list');
interest.focus();
return false;
}
else {
alert('Form is Successfully Submitted, thank you');
window.location.reload()
return true;
}
}
Here is my html code:
<form action="http://******/cgi-bin/echo_form" method="post" name="joinform" onsubmit="return check_compulsory(joinform);">
<form action="http://********/cgi-bin/echo_form" method="post" name="joinform" onsubmit="return formValidation();">
<form name="loginform" onsubmit="return loginValidation();">
<table style="margin: 0px auto;">
<tr>
<td>UserName:</td>
<td><input type="text" name="UserName" value="" size="20" maxlength="40" /></td>
<td></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="Password" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
</table>
<div style=margin-left:475px;>
<input type="submit" value="Sign In" />
</div>
</form>
<br>
<h1>Join Us Today!</h1>
<p>Please complete this simple form to Sign Up to CWON-Australia!</p>
<p style=color:blue;>*CompulsoryField</p>
<form action="http://******/cgi-bin/echo_form" method="post" name="joinform" onsubmit="return check_compulsory(joinform);">
<form action="http://******/cgi-bin/echo_form" method="post" name="joinform" onsubmit="return formValidation()">
<form name="joinform" onsubmit="return formValidation()">
<table>
<tr>
<td>First Name:*</td>
<td><input type="text" name="firstname" value="" size="20" maxlength="40" /></td>
<td></td>
</tr>
<tr>
<td>Middle Name:</td>
<td><input type="text" name="middlename" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>Last Name:*</td>
<td><input type="text" name="lastname" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>Date Of Birth*</td>
<td><input type="text" name="dateofbirth" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>Nationality</td>
<td><input type="text" name="nationality" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>Preferred Contact Method: *</td>
<td><input type="radio" name="preferredcontact" id="cl" value="L" /> Landline</td>
</tr>
<tr>
<td></td>
<td><input type="radio" name="preferredcontact" id="cm" value="M" /> Mobile</td>
</tr>
<tr>
<td></td>
<td><input type="radio" name="preferredcontact" id="ce" value="E" checked="checked" /> E-Mail</td>
</tr>
<tr>
<td>Landline Phone Number:</td>
<td><input type="text" name="dayphone" value="" size="20" maxlength="20" /></td>
</tr>
<tr>
<td>Mobile Phone Number:</td>
<td><input type="text" name="mobphone" value="" size="20" maxlength="20" /></td>
</tr>
<tr>
<td>e-Mail Address: *</td>
<td><input type="text" name="email" value="" size="30" maxlength="30" /></td>
</tr>
<tr>
<td>Address Line 1: *</td>
<td><input type="text" name="address1" value="" size="40" maxlength="40" /></td>
</tr>
<tr>
<td>Address Line 2: *</td>
<td><input type="text" name="address2" value="" size="40" maxlength="40" /></td>
<td></td>
</tr>
<tr>
<td>Postcode: *</td>
<td><input type="text" name="postcode" value="" size="4" maxlength="4" /></td>
<td></td>
</tr>
<tr>
<td>City: *</td>
<td><input type="text" name="city" value="" size="25" maxlength="25" /></td>
<td></td>
</tr>
<tr>
<td>State: *</td>
<td>
<select name="state" size="1">
<option selected = "selected">Please Choose</option>
<option>NSW</option>
<option>VIC</option>
<option>WA</option>
<option>SA</option>
<option>TAS</option>
<option>QLD</option>
<option>ACT</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td>Occupation:</td>
<td><input type="text" name="occupation" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>Hobbies:</td>
<td><input type="text" name="hobbies" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>You Are Interested in:* </td>
<td>
<select name="interest" size="1">
<option selected = "selected">Please Choose</option>
<option>Fund Raisers</option>
<option>Domestic Volunteering</option>
<option>Foreign Volunteering</option>
<option>All of Them</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" name="TandC" id="TandC" value="yes" checked="checked"> </td>
<td>I have read the Terms & Conditions of being the member of CWON-Australia, and I agree to abide by the rules and regulations.</td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" name="newsletter" id="newsletter" value="yes" checked="checked"></td>
<td>Sign Up for CWON-Australia Newsletter.</td>
<td></td>
</tr>
<tr>
<td></td>
<td><input type="hidden" name="signupdate" value="" /></td>
<td></td>
</tr>
</table>
<div align="right">
<input type="reset" value="Reset" onclick="set_focus()" />
<input type="submit" value="Join Now!" />
</div>
</form>
Delete all your messy code and try jQuery.validate or Really simple validation .
You are welcome~
Check out AngularJS. If you're writing large javascript-oriented web applications it can make your life a lot easier.

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>

Categories

Resources