I am using Regex to check my user input and then adding to an empty array called message when an error is found. I am having trouble displaying these errors along the top of the form
I am using Regex to check my user input and then adding to an empty array called message when an error is found. I am having trouble displaying these errors along the top of the form
<script>
function emailCheck(email) {
var re = /^[a-zA-Z\d]+\.[a-zA-Z\d]+#mohawkcollege.(?:com|ca|org)$/;
return re.test(email);
}
function phoneCheck(phone) {
var re = /^\b\d{3}[-.]?\d{3}[-.]?\d{4}\b$/;
return re.test(phone);
}
function postalCheck(postal){
var re = /^([a-zA-Z]\d[a-zA-Z])[\s\-]?(\d[a-zA-Z]\d)+$/;
return re.test(postal);
}
function streetCheck(street) {
var re = /^[1-9]{2,3} +[a-zA-Z]+ +(Street|street|road|Road)+$/;
return re.test(street);
}
function nameCheck(fname) {
var re = /^(mr\.|mrs\.|Mr\.|Mrs\.)\s+[a-zA-Z]+\s+[a-zA-Z]+$/;
return re.test(fname);
}
function errorCheck() {
var message = "";
var email = document.forms["myForm"]["email"].value;
var phone = document.forms["myForm"]["phone"].value;
var postal = document.forms["myForm"]["postal"].value;
var fname = document.forms["myForm"]["fname"].value;
var street = document.forms["myForm"]["street"].value;
if(phoneCheck(phone)) {
alert (phone + " is valid");
}
else{
message += "Phone invalid";
}
if(postalCheck(postal)) {
alert (postal + " is valid");
}
else {
message += "Postal invalid";
}
if (nameCheck(fname)) {
alert (fname + " is valid");
}
else {
message += "name invalid";
}
if (streetCheck(street)) {
alert (street + " is valid");
}
else {
message += "Street invalid";
}
if (emailCheck(email)) {
alert (email + " is valid");
}
else {
message += "email invalid";
}
return false;
$("#errorMessage").html(message);
}
</script>
here is the HTML
<html>
<body>
<p id="errorMessage"></p>
<link rel='stylesheet' type='text/css' href='Lab4.css'>
<table>
<tr>
<td class="top">
<a href=<?PHP echo $_SERVER["PHP_SELF"] ?>> Refresh ThisPage </a>
</td>
<td class="top">
Show Logfile.txt
</td>
<td class="top">
Show Logfile.txt Formatted
</td>
<td class="top">
Clear logfile.txt
</td>
</tr>
</table>
<form name="myForm" onsubmit="errorCheck()">
<table class="body">
<tr>
<td class="column1">
Full Name:
</td>
<td class="column2">
<input id="fname" type="text" >
</td>
<td class="column3">
Salution of Mr. and Mrs. followed by two text strings separated by any number of spaces
</td>
</tr>
<tr>
<td class="column1">
Street:
</td>
<td class="column2">
<input id="street" type="text" >
</td>
<td class="column3">
2 or 3 digit number followed by a text string ending with Street or Road separated by any number of space
</td>
</tr>
<tr>
<td class="column1">
PostalCode:
</td>
<td class="column2">
<input id = "postal" type="text" >
</td>
<td class="column3">
Char Char Digit optional Hyphen or space Char Digit Digit (abclxyz and number 0 not allowed. Case insensitive
</td>
</tr>
<tr>
<td class="column1">
Phone:
</td>
<td class="column2">
<input id = "phone" type="text" >
</td>
<td class="column3">
10 digits, first 3 digits have optional parentheses, either side of digits 456 are optional space, dot or hyphen
</td>
</tr>
<tr>
<td class="column1">
Email:
</td>
<td class="column2">
<input id="email" type="text">
</td>
<td class="column3">
firstname.lastname#mohawkcollege.domain (firstname and lastname must be 4-10 characters in length, domain may be either .com, .ca or .org)
</td>
</tr>
</table>
<br>
<input class="submit" type="submit" id="check" value="Submit me now!!!"/>
</form>
</body>
</html>
You are returning from errorCheck() before you set the content of #errorMessage.
I moved the html() call before return and made message an array (as you said) so you can display the messages in a list format.
function emailCheck(email) {
var re = /^[a-zA-Z\d]+\.[a-zA-Z\d]+#mohawkcollege.(?:com|ca|org)$/;
return re.test(email);
}
function phoneCheck(phone) {
var re = /^\b\d{3}[-.]?\d{3}[-.]?\d{4}\b$/;
return re.test(phone);
}
function postalCheck(postal) {
var re = /^([a-zA-Z]\d[a-zA-Z])[\s\-]?(\d[a-zA-Z]\d)+$/;
return re.test(postal);
}
function streetCheck(street) {
var re = /^[1-9]{2,3} +[a-zA-Z]+ +(Street|street|road|Road)+$/;
return re.test(street);
}
function nameCheck(fname) {
var re = /^(mr\.|mrs\.|Mr\.|Mrs\.)\s+[a-zA-Z]+\s+[a-zA-Z]+$/;
return re.test(fname);
}
function errorCheck() {
var message = [];
var email = document.forms["myForm"]["email"].value;
var phone = document.forms["myForm"]["phone"].value;
var postal = document.forms["myForm"]["postal"].value;
var fname = document.forms["myForm"]["fname"].value;
var street = document.forms["myForm"]["street"].value;
if (phoneCheck(phone)) {
alert(phone + " is valid");
} else {
message.push("Phone invalid");
}
if (postalCheck(postal)) {
alert(postal + " is valid");
} else {
message.push("Postal invalid");
}
if (nameCheck(fname)) {
alert(fname + " is valid");
} else {
message.push("name invalid");
}
if (streetCheck(street)) {
alert(street + " is valid");
} else {
message.push("Street invalid");
}
if (emailCheck(email)) {
alert(email + " is valid");
} else {
message.push("email invalid");
}
$("#errorMessage").html(`<ul><li>${message.join('</li><li>')}</li></ul>`);
return false;
}
#errorMessage {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="errorMessage"></p>
<table>
<tr>
<td class="top">
</td>
<td class="top"> Show Logfile.txt </td>
<td class="top"> Show Logfile.txt Formatted </td>
<td class="top"> Clear logfile.txt </td>
</tr>
</table>
<form name="myForm">
<table class="body">
<tr>
<td class="column1">Full Name:</td>
<td class="column2">
<input id="fname" type="text">
</td>
<td class="column3">Salution of Mr. and Mrs. followed by two text strings separated by any number of spaces</td>
</tr>
<tr>
<td class="column1">Street:</td>
<td class="column2">
<input id="street" type="text">
</td>
<td class="column3">2 or 3 digit number followed by a text string ending with Street or Road separated by any number of space</td>
</tr>
<tr>
<td class="column1">PostalCode:</td>
<td class="column2">
<input id="postal" type="text">
</td>
<td class="column3">Char Char Digit optional Hyphen or space Char Digit Digit (abclxyz and number 0 not allowed. Case insensitive</td>
</tr>
<tr>
<td class="column1">Phone:</td>
<td class="column2">
<input id="phone" type="text">
</td>
<td class="column3">10 digits, first 3 digits have optional parentheses, either side of digits 456 are optional space, dot or hyphen</td>
</tr>
<tr>
<td class="column1">Email:</td>
<td class="column2">
<input id="email" type="text">
</td>
<td class="column3">firstname.lastname#mohawkcollege.domain (firstname and lastname must be 4-10 characters in length, domain may be either .com, .ca or .org)</td>
</tr>
</table>
<br>
<input class="submit" type="button" onclick="errorCheck()" id="check" value="Submit me now!!!" />
</form>
Related
This question already has answers here:
How does the single equal sign work in the if statement in javascript
(6 answers)
What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)
(5 answers)
Closed 3 years ago.
Hello guys I'm really new to javascript,
I want an alert message to appear if the user pressed on check,
to see if the input was right or wrong,
and I've been trying for so long but it's not working no matter what, it's just a simple code.
I'm really suffering with this for hours, trying to figure why no alert message appears when I press on the check button.
Would be really grateful for any help or any tip, many thanks!!
function myFunction() {
var x = document.getElementById("f").value;
var z = document.getElementById("s").value;
var c = document.getElementById("e").value;
var v = document.getElementById("p").value;
var b = document.getElementById("p1").value;
if (isNaN(x) || x = "") {
alert("First Name input is wrong");
} else {
alert("Input is ok");
}
if (isNaN(z) || z = "") {
alert("Second Name input is wrong");
} else {
alert("Input is ok");
}
if (isNaN(c) || c = "") {
alert("Email input is wrong");
} else {
alert("Input is ok");
}
if (v = "") {
alert("Input is wrong");
} else {
alert("Input is ok");
}
if (b = "" || b !== v) {
alert("Password does not match");
else {
alert("Input is ok");
}
}
}
<div class="event">
<h1> Event Planning</h1>
</div>
<div class="back">
<table border="1">
<form action="submit.php" method="post">
<tr>
<th colspan="2"> Sign UP</th>
</tr>
<tr>
<td> First Name </td>
<td> <input type="text" name="FirstName" id="f"></td>
</tr>
<tr>
<td> Second Name</td>
<td> <input type="text" name="SecondName" id="s"></td>
</tr>
<tr>
<td> Email Address</td>
<td> <input type="email" name="email" id="e"> </td>
</tr>
<tr>
<td> Password</td>
<td> <input type="password" name="psd" id="p"> </td>
</tr>
<tr>
<td> Repeat Password</td>
<td> <input type="password" name="psd2" id="p1"> </td>
</tr>
<tr>
<td colspan="2"> <input type="submit" name="submit" value="submit">
<button type="button" id="but" onclick="myFunction()">Check</button></td>
</tr>
</form>
</table>
You have a few syntax errors in your function.
Javascript requires == (or ===) for comparisons.
You also need to add a curly brace } before the else after "Password does not match", and remove one after the following "Input is ok".
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.
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.)
i have one form that validate form fields with javascript and sending email with VBscript. how ever validation works fine but email not sent to email account.
VBScript to sending email:
<%
posted = request.form ("submit")
if posted = "Submit" then
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' Customize the following 5 lines with your own information. ''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
vtoaddress = "___________" ' Change this to the email address you will be receiving your notices.
vmailhost = "smtp.gmail.com" ' Change this to your actual Domain name.
vfromaddress = "___________" ' Change this to the email address you will use to send and authenticate with.
vfrompwd = "___________" ' Change this to the above email addresses password.
'''''''''''''''''''''''''''''''''''''''''''
'' DO NOT CHANGE ANYTHING PAST THIS LINE ''
'''''''''''''''''''''''''''''''''''''''''''
vsubject = request.form ("subject")
vfromname = request.form ("fname")
vbody = request.form ("message")
vrplyto = request.form ("email")
vrcity = request.form ("city")
vrmono = request.form ("phone")
vmsgbody = "<b>Name:</b> "& vfromname & "<br><b>Email:</b> "& vrplyto &"<br><b>Mobile No:</b> "& vrmono &"<br><b>City:</b> "& vrcity &"<br><b>Subject:</b> "& vsubject&"<br><b>Message:</b> "& vbody
Set objEmail = Server.CreateObject("CDO.Message")
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = vmailhost
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = vfromaddress
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = vfrompwd
objEmail.Configuration.Fields.Update
objEmail.Subject = vsubject
objEmail.From = vfromaddress
objEmail.To=vfromaddress
objEmail.HTMLBody = vmsgbody
objEmail.Send
vErr = Err.Description
if vErr <> "" then
response.write vErr & "<br><br>There was an error on this page."
'MsgBox("There was an error on this page.")
else
response.write "Thank you, your message has been sent."
'MsgBox("Thank you, your message has been sent.")
End If
Set objEmail = Nothing
response.write "Thank you, your message has been sent."
'MsgBox("Thank you, your message has been sent.")
end if
%>
Javascript to validate form:
<script language="JavaScript">
<!--
function validate()
{
var count_bug=0;
if(document.form1.fname.value=="")
{
document.getElementById("alertMsgfname").innerHTML=" Enter Your First Name. ";
document.getElementById("alertMsgfname").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.fname.focus();
count_bug+=1;
}
if(document.form1.email.value=="")
{
document.getElementById("alertMsgemail").innerHTML=" Enter Your E-mail. ";
document.getElementById("alertMsgemail").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.email.focus();
count_bug+=1;
}
else if(!isEmail(document.form1.email.value))
{
document.getElementById("alertMsgemail").innerHTML=" Enter Valid E-mail! ";
document.getElementById("alertMsgemail").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.email.focus();
count_bug+=1;
}
if(document.form1.phone.value=="")
{
document.getElementById("alertMsgphone").innerHTML=" Your Phone No. ";
document.getElementById("alertMsgphone").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.phone.focus();
count_bug+=1;
}
else if(!ValidateNo(document.form1.phone.value," 1234567890,-/+"))
{
document.getElementById("alertMsgphone").innerHTML=" Invalid Phone No. ";
document.getElementById("alertMsgphone").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.phone.focus();
count_bug+=1;
}
else if(document.form1.phone.value.length < 5)
{
document.getElementById("alertMsgphone").innerHTML=" Invalid Phone No. ";
document.getElementById("alertMsgphone").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.phone.focus();
count_bug+=1;
}
if(document.form1.city.value=="")
{
document.getElementById("alertMsgCity").innerHTML=" Enter Your City Name. ";
document.getElementById("alertMsgCity").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.city.focus();
count_bug+=1;
}
if(document.form1.subject.value=="")
{
document.getElementById("alertMsgSubject").innerHTML=" Enter Your Subject. ";
document.getElementById("alertMsgSubject").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.subject.focus();
count_bug+=1;
}
if(document.form1.message.value=="")
{
document.getElementById("alertMsgMessage").innerHTML=" Enter Your Message. ";
document.getElementById("alertMsgMessage").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.message.focus();
count_bug+=1;
}
if(count_bug>0)
return false;
else
return true;
}
function isEmail (emailIn){
var isEmailOk = false;
var filter = /^[a-zA-Z0-9][a-zA-Z0-9._-]*\#[a-zA-Z0-9-]+(\.[a-zA-Z][a-zA-Z-]+)+$/
// var filter = /^(([^<>()[\]\\.,;:\s#\”]+(\.[^<>()[\]\\.,;:\s#\”]+)*)|(\”.+\”))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
if(emailIn.search(filter) != -1)
isEmailOk = true;
if(emailIn.indexOf("..") != -1)
isEmailOk = false;
if(emailIn.indexOf(".#") != -1)
isEmailOk = false;
return isEmailOk;
}
function ValidateNo( NumStr, String )
{
for( var Idx = 0; Idx < NumStr.length; Idx ++ )
{
var Char = NumStr.charAt( Idx );
var Match = false;
for( var Idx1 = 0; Idx1 < String.length; Idx1 ++)
{
if( Char == String.charAt( Idx1 ) )
Match = true;
}
if ( !Match )
return false;
}
return true;
}
</script>
html form code:
<form name="form1" method="post" onsubmit="return validate();">
<table border="0" width="100%" cellspacing="0" cellpadding="0" class="table-format">
<tr valign="middle">
<td align="left" class="text-fm" width="23%" style="padding-top:8px;">
<b>Name<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm" width="5%">
<b>:</b></td>
<td class="text-fm" align="left">
<input type="text" name="fname" id="fname" size="43" maxlength="40" class="inp">
<span id="alertMsgfname" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr valign="middle">
<td align="left" class="text-fm" style="padding-top:8px;">
<b>Email Id<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm">
<b>:</b></td>
<td class="text-fm" align="left">
<input type="text" name="email" id="email" size="43" maxlength="76" class="inp">
<span id="alertMsgemail" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr valign="middle">
<td align="left" class="text-fm" style="padding-top:8px;">
<b>Mobile No.<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm">
<b>:</b></td>
<td class="text-fm" align="left">
<input type="text" name="phone" id="phone" size="43" maxlength="16" class="inp">
<span id="alertMsgphone" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr valign="middle">
<td align="left" class="text-fm" style="padding-top:8px;">
<b>City<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm">
<b>:</b></td>
<td class="text-fm" align="left">
<input type="text" name="city" id="city" size="43" maxlength="76" class="inp">
<span id="alertMsgCity" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr valign="middle">
<td align="left" class="text-fm" style="padding-top:8px;">
<b>Subject<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm">
<b>:</b></td>
<td class="text-fm" align="left">
<input type="text" name="subject" id="subject" size="43" maxlength="76" class="inp">
<span id="alertMsgSubject" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr valign="middle">
<td align="left" class="text-fm" style="padding-top:8px;">
<b>Message<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm">
<b>:</b></td>
<td class="text-fm" align="left">
<textarea name="message" id="message" size="43" maxlength="16" class="inp" rows="6" cols="30"></textarea>
<span id="alertMsgMessage" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr>
<td align="left" colspan="3">
<div align="center"><br>
<input type="submit" value="" name="Submit" class="imgClass"/>
<br>
</td>
</tr>
</table>
</form>
Absence of an error description doesn't imply the absence of an error. Change your error handling code to this:
If Err Then
response.write Err.Number & "<br><br>There was an error on this page."
Else
response.write "Thank you, your message has been sent."
End If
Are you able to connect from your webserver to the mailserver on port 465?
telnet smtp.gmail.com 465
Are you using correct credentials?
Do you have access to the mailserver logs? What do they say about connections from that page? If you don't have access to the actual mailserver, can you set up a dummy server and temporarily point the page to that server, so you can check if the code is working in principle?
Basically my HTML looks like this:
<form method="post" name="htmlform" onsubmit = "checkFields()">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" size="30" maxlength="50"/>
/td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio" name="sex"
value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
When the form is submitted, the onsubmit() event checks if first_name textfield is blank, if it is then the label or span to its left is appended to output "first name*" + " you must enter a first name" and similarly for last name and sex.
The problem is that the text in the table does not update with appendchild. When I enclosed the statement in an alert for debugging the message is appended then disappears.
The JavaScript code is below for the onsubmit = "checkFields()".
function checkFields() {
var firstName = document.getElementById("first_name").value;
var lastName = document.getElementById("last_name").value;
if (firstName == "") {
//<span style='color:red'> Please enter a first name </span>
var nameHint = " Please enter a first name";
var node = document.getElementById("firstNameSpan");
//alert(node.appendChild(document.createTextNode(nameHint)) );
//not working
node.appendChild(document.createTextNode(nameHint));
} if (lastName == "") {
//additional code
}
}
Thanks in advance, your help is much appreciated. Also are there any JavaScript debuggers?
Regards
David D
I believe your sample code is not working due to incorrect html. document.getElementById("last_name") will return undefined.
http://jsfiddle.net/5E6my/1/
Thanks all, Im getting the ropes of JFiddle the split screen is very useful although the error messages are not useful for debugging. Here is the completed code (1) HTML (2) JavaScript.
<form method="post" name="htmlform" onsubmit="return checkFields();">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" id="last_name" size="30"
maxlength="50" /></td>
</tr>
<tr>
<td style="text-align: center;" colspan="2" id = "sexMessage">
Please select Male or Female*</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio"
name="sex" value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
The JavaScript code to react to the onsubmit button's unfilled fields in the form are: (any ways to make this code simpler??)
window.checkFields = function()
{
var firstName = document.getElementById("first_name");
var lastName = document.getElementById("last_name");
if(firstName.value == "")
{
//<span style='color:red'> Please enter a first name </span>
var nameHint = " *Please enter a first name ";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="red";
} else{
var nameHint = " First Name *";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="black";
}
if (lastName.value == "")
{
//additional code
var nameHint = " *Please enter a last name";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="red";
} else{
var nameHint = " Last Name *";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="black";
}
var radios = document.getElementsByName("sex");
var radioValue = ""
for(var i=0; i<radios.length; i++)
{
if(radios[i].checked)
{
radioValue = radios[i].value;
}
}
if(radioValue === "")
{
var sexNode = document.getElementById("sexMessage");
var nameHint = "*You did not choose a sex";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="red";
} else {
var sexNode = document.getElementById("sexMessage");
var nameHint = "Please select Male or Female*";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="black";
}
return false;
}
The trick is to use as Yury suggested was the onsubmit="return checkfields()" and then in the code block to use window.checkFields = function() { etc.
One question that I have... is JQuery a lot simpler to use, im learning JavaScript before JQuery... should I skip to JQUery instead. Also does JQuery support the AJAX framework?
Much appreciated
David