A part of the application I am creating asks the user to enter the state of their current residence, it then asks the user to enter their postcode. The program then tests to see if the postcode is valid for that State.
Eg. State entered "VIC" postcode can't be >=4000 or < 3000
Instead of either receiving the error message or not, I constantly receive the error message even when the postcode is valid
JS for my WebPage
function validate () {
var result = true
var errMsg = " "
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").value;
var other = document.getElementById("text").value;
if (state == "VIC" || postcode >= 4000 || postcode < 3000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "VIC" || postcode >=9000 || postcode < 8000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "NSW" || postcode >=3000 || postcode < 1000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "QLD" || postcode <4000 || postcode >= 5000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen stae\n"
result = false;
}
else if (state == "QLD" || postcode <9000 || postcode >= 10000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "NT" || postcode >= 1000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "WA" || postcode < 6000 || postcode >= 7000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "SA" || postcode < 5000 || postcode >= 6000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "TAS" || postcode < 7000 || postcode >= 8000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
else if (state == "ACT" || postcode >= 1000) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n"
result = false;
}
if (document.getElementById("other").checked = true || other == "If you selected Other, enter your answer here...") {
errMsg = errMsg + "You have selected other, please enter your answer into the text box provided"
result = false;
}
if (errMsg != "") {
document.getElementById("errMessage").value = errMsg;
}
return result;
}
function init() {
if (document.getElementById("applypage")!=null) {
var regForm = document.getElementById("regform");
job_apply();
regForm.onsubmit = validate;
}
else if (document.getElementById("jobspage") !=null) {
storeJobNumber();
}
}
window.onload = init;
HTML for my webPage
<!DOCTYPE html>
<html Lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="CWA HELP DESK" />
<meta name="keywords" content="HTML, CWA, Help, Desk" />
<meta name="author" content ="Harry Keys" />
<title>Application Form</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<script src="apply.js"></script>
</head>
<body id="applypage">
<form id="regform" method="post" action="http://mercury.swin.edu.au/it000000/formtest.php" novalidate="novalidate">
<img src="images/logo.png" alt="Company Logo" />
<h1> Job Application Form </h1>
<fieldset>
<p><label for="jobNumber">Job Reference Number</label>
<input type="text" onkeyup="this.value=this.value.replace(/[^\d]/,'')" name="jobNumber" id="jobNumber" maxlength="5" size="7" required="required" readonly/>
</p>
<p><label for="givenName">Given Name</label>
<input type="text" onkeypress="return /[a-z]/i.test(event.key)" name="givenName" id="givenName" maxlength="20" size="15" required="required"/>
<label for="familyName">Family Name</label>
<input type="text" onkeypress="return /[a-z]/i.test(event.key)" name="familyName" id="familyName" maxlength="20" size="15" required="required"/>
</p>
</fieldset>
<fieldset>
<legend>Personal Details</legend>
<p><label for="dob">Date of Birth</label>
<input type="date" name="dob" id="dob" required="required"/>
</p>
<p><label for="staddress">Street Address</label>
<input type="text" name="staddress" id="staddress" maxlength="40" required="required"/>
<label for="suburb">Suburb/Town</label>
<input type="text" name="suburb" id="suburb" maxlength="40" required="required"/>
</p>
<p><label for="state">State</label>
<select name="state" id="state">
<option value="Please Select">Please Select</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="ACT">ACT</option>
</select>
</p>
<p><label for="postcode">Postcode</label>
<input type="text" name="postcode" id="postcode" onkeyup="this.value=this.value.replace(/[^\d]/,'')" maxlength="4" size="4" required="required"/>
</p>
<p><label for="email">Email</label>
<input type="email" name="email" id="email" required="required"/>
</p>
<p><label for="phonenumber">Phone Number</label>
<input type="text" name="phonenumber" id="phonenumber" onkeyup="this.value=this.value.replace(/[^\d]/,'')" maxlength="12" size="12" required="required"/>
<fieldset>
<legend>Gender</legend>
<p> <label for="male">Male</label>
<input type="radio" id="male" name="Gender" value="male" required="required"/>
<label for="female">Female</label>
<input type="radio" id="female" name="Gender" value="female"/>
<label for="other">Other</label>
<input type="radio" id="undefined" name="Gender" value="undefined"/>
</p>
</fieldset>
<fieldset>
<legend>Skills List</legend>
<p> <label for="teamwork">Teamwork</label>
<input type="checkbox" id="teamwork" name="Skill[]" value="Teamwork" checked="checked"/>
<label for="rubyskills">Ruby Experience</label>
<input type="checkbox" id="rubyskills" name="Skill[]" value="Rubyskills"/>
<label for="efficiency">Efficiency</label>
<input type="checkbox" id="efficiency" name="Skill[]" value="Efficiency"/>
<label for="communication">Communication</label>
<input type="checkbox" id="communication" name="Skill[]" value="Communication"/>
<label for="other">Other</label>
<input type="checkbox" id="other" name="Skill[]" value="other"/>
</p>
<p> <textarea id="text" name="Skill[]" rows="5" cols="20" placeholder="If you selected Other, enter your answer here..."></textarea>
</p>
</fieldset>
</fieldset>
<p> <textarea id="errMessage" rows="3" cols="40"></textarea> </p>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset Form"/>
</form>
When I select "NSW" and enter a postcode that is not >=3000 or <1000 I should not receive an error. But I still do
I think your if-else-if construct is a little bit confusing.
I'd recommend a switch-block to validate which state has been chosen and with each case check if the postcode is in the correct range.
Something like:
function validate() {
var result = true
var errMsg = " "
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").value;
var other = document.getElementById("text").value;
switch (state) {
case "VIC":
if (postcode >= 3000 && postcode < 4000) {
result = true;
}
break;
case "NSW":
if (postcode >= 1000 && postcode < 3000) {
result = true;
}
break;
case "QLD":
if (postcode >= 4000 && postcode < 5000) {
result = true;
}
break;
}
if (!result) {
errMsg = errMsg + "You have entered an invalid postcode for your chosen state\n";
}
if (document.getElementById("other").checked = true || other == "If you selected Other, enter your answer here...") {
errMsg = "You have selected other, please enter your answer into the text box provided"
result = false;
}
if (errMsg != "") {
document.getElementById("errMessage").value = errMsg;
}
return result;
}
Related
I'm trying to get my HTML & Javascript code to generate a similar prompt (see image below something similar in principle). Instead of the prompt working a page called "HTML - Form Data Extraction Test" comes up instead.
Struggling to pin point where I'd gone wrong as my labels and ID's are in place, I've been using "getelementbyid", defined all the instances of when the messages should appear.
Any help would be greatly appreciated. Thanks in advance.
/* function validate()will validate form data */
function validate() {
var jref = document.getElementById("jref").value;
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var dob = document.getElementById("dob").value;
var email = document.getElementById("email").value;
var genm = document.getElementById("genm").checked;
var genf = document.getElementById("genf").checked;
var saddress = document.getElementById("saddress").value;
var stown = document.getElementById("stown").value;
var pnumber = document.getElementById("pnumber").value;
//NEED LABELS FOR
//state dropdown
//Skills drop down
var errMsg = "";
var result = true; /* assumes no errors */
//var pattern = /^[a-zA-Z ]+$/; /* regular expression for letters and spaces only */
if (jref == "") {
errMsg += "Job Reference Number cannot be Empty\n";
//errMsg = errMsg + "First Name cannot be
}
if (fname == "") {
errMsg += "First Name cannot be Empty\n";
}
if (lname == "") {
errMsg += "Last Name cannot be Empty\n";
}
if (dob == "") {
errMsg += "Date of Birth cannot be Empty\n";
}
if (email == "") {
errMsg += "Email cannot be Empty\n";
}
if ((genm == "") && (genf == "")) { //check whether gender is selected
errMsg += "A gender must be selected.\n";
}
if (saddress == "") {
errMsg += "Street Address cannot be Empty\n";
}
if (stown == "") {
errMsg += "Suburb or Town cannot be Empty\n";
}
if (pnumber == "") {
errMsg += "Phone Number cannot be Empty\n";
}
if (errMsg != "") {
alert(errMsg);
result = false;
}
return result;
}
function init() {
/* assign the <form> element to variable regForm */
var appForm = document.getElementById("appForm");
/* link function validate() to the onsubmit event of the form */
appForm.onsubmit = validate;
}
/* execute function init() once the window is loaded*/
window.onload = init;
<main>
<!-- Start of the form that the user fills out -->
<form method="post" action="http://mercury.swin.edu.au/it000000/formtest.php" id="appForm">
<h1>Job Application Form</h1>
<label for="jref">Job Reference Number</label><br>
<input type="text" name="jref" maxlength="5" id="jref" pattern="\d{4}" /><br>
<fieldset>
<label for="fname">First Name</label><br>
<input type="text" id="fname" maxlength="20" name="fname" /> <br>
<label for="lname">Last Name</label><br>
<input type="text" id="lname" maxlength="20" name="lname" /><br>
<label for="dob">Date of birth:</label><br>
<input id="dob" type="date" name="dob" /><br>
<label>Gender</label>
<input id="genm" type="radio" name="genm" value="Male" />
<label for="genm">Male</label>
<input id="genf" type="radio" name="genf" value="Female" />
<label for="genf">Female</label><br>
<label for="saddress">Street Address</label><br>
<input type="text" id="saddress" maxlength="40" name="saddress" /><br>
<label for="stown">Suburb/Town</label><br>
<input type="text" id="stown" maxlength="40" name="stown" /><br> State
<br>
<select name="slRank">
<option value="">Choose</option>
<option value="8">ACT</option>
<option value="8">ACT</option>
<option value="7">TAS</option>
<option value="6">SA</option>
<option value="5">WA</option>
<option value="4">NT</option>
<option value="3">QLD</option>
<option value="2">NSW</option>
<option value="1">VIC</option>
</select><br>
<label for="email">Email Address</label><br>
<input type="email" id="email" name="email" placeholder="example#gmail.com" /><br>
<label for="pnumber">Phone Number</label><br>
<input type="tel" id="pnumber" name="pnumber" placeholder="(##) ####-####" /><br> Skills
<select name="slRank">
<option value="">Choose</option>
<option value="9">Creativity</option>
<option value="8">Interpersonal Skills</option>
<option value="7">Critical Thinking</option>
<option value="6">Problem Solving</option>
<option value="5">Public Speaking</option>
<option value="4">Communication</option>
<option value="3">Collaboration</option>
<option value="2">Accounting</option>
<option value="1">Other</option>
</select><br /><br />
<label>Other Skills</label>
<br />
<textarea autofocus="autofocus" placeholder="Please fill out other skills you have here."></textarea><br>
<input type="submit" value="Apply" />
<input type="reset" value="Reset" />
</fieldset>
</form>
</main>
user this https://jqueryvalidation.org/ js library for form validation
I am currently doing a unit task and am having trouble working out why my javascript wont connect. i have tried a few things but cant seem to work it out. Im sure its easy but i just cant work it out. an explanation would be great too.
There are two files one html and one javascript.
Thanks in advance
HTML
<script src="validate.js"></script>
</head>
<body>
<header>
<h1>Rohirrim Ranch Tours</h1>
<h2>Booking Form</h2>
</header>
<form id="regform" method="post"
action="https://mercury.swin.edu.au/it000000/formtest.php"
novalidate="novalidate">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="firstname">Enter your first name</label>
<input type="text" name="firstname" id="firstname" size="20"
/>
</p>
<p><label for="lastname">Enter your last name</label>
<input type="text" name="lastname" id="lastname" size="20" />
</p>
<fieldset id="species">
<legend>Species:</legend>
<label for="human">Human</label>
<input type="radio" name="species" id="human"
value="Human"/><br />
<label for="dwarf">Dwarf</label>
<input type="radio" name="species" id="dwarf"
value="Dwarf" /><br />
<label for="elf">Elf</label>
<input type="radio" name="species" id="elf"
value="Elf" /><br />
<label for="hobbit">Hobbit</label>
<input type="radio" name="species" id="hobbit"
value="Hobbit" /><br />
</fieldset>
<p><label for="age">Enter your age</label>
<input type="text" id="age" name="age" size="5">
</p>
<p><label for="beard">Enter your beard length in inches</label><br />
0 <input type="range" id="beard" name="beard" min="0"
max="60"> 60
</p>
</fieldset>
<fieldset id="trip">
<legend>Your trip:</legend>
<fieldset>
<legend>Booking:</legend>
<label for="1day">1 Day Tour - $200 </label>
<input type="checkbox" name="1day" id="1day"
value="1day" /><br />
<label for="4day">4 Day Tour - $1500</label>
<input type="checkbox" name="4day" id="4day"
value="4day" /><br />
<label for="10day">10 Day Tour - $3000</label>
<input type="checkbox" name="10day" id="10day"
value="10day" /><br />
</fieldset>
<p>
<label for="food">Menu preferences</label>
<select name="food" id="food">
<option value="none">Please select</option>
<option value="lembas">Lembas</option>
<option value="mushrooms">Mushrooms</option>
<option value="ent">Ent Draft</option>
<option value="cram">Cram</option>
</select>
</p>
<p>
<label for="partySize">Number of Travellers</label>
<input type="text" id="partySize" name="partySize"
maxlength="3" size="3" />
</p>
</fieldset>
<div id="bottom"> </div>
<p><input type="submit" value="Book Now!" />
<input type="reset" value="Reset" />
</p>
</form>
JAVASCRIPT
"use strict";
function validate() {
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var errMsg = "";
var result = true;
if (!firstname.match(/^[a-zA-Z]+$/)) {
errMsg = errMsg + "Your first name must only contain alpha
characters\n";
result = false; }
if (!lastname.match(/^[a-zA-Z+$]/)){
errMsg = errMsg + "Your last name must only contain alpha
characters\n";
result = false;
}
var age = document.getElementById("age").value;
if (isNaN(age)){
errMsg = errMsg + "your age must be a number\n"
result = false;
}
else if (age < 18) {
errMsg = errMsg +" your age must be 18 or older\n";
result = false;
}
else if (age >= 10000) {
errMsg = errMsg + "your age must be between 18 and 10000\n";
result = false;
}
var partySize = document.getElementById("partySize").value;
if (isNaN(partySize)) {
errMsg = errMsg + "your age must be a number\n"
result = false;
}
else if (partySize < 1) {
errMsg = errMsg +" party size must be greater than 0\n";
result = false;
}
else if (age >= 100) {
errMsg = errMsg + "your party size must be less or equal to 100\n";
result = false;
}
if (erMsg !== ""){
alert(errMsg);
}
return result;
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
I see your error erMsg instead of errMsg
if (erMsg !== ""){
alert(errMsg);
}
and also add event.preventDefault(); at the beginning of the validate function
Your js reference is fine :)
Try setting the Javascript url as './validate.js'
I currently trying to make a website with a validating booking form for a university a project about a university portal. It used to work with my javascript validation until I added to validate time. Problem is sumbit button not working when I add to validate time and whenever I remove it is working.
HTML and JavaScript
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Any suggestions?
You should do this kind of thing with required.
<input type="email" required>
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
(https://www.w3schools.com/tags/att_input_required.asp)
There also exist pattern. For example, if you want to allow only six letters
<input type="text" pattern="[A-Za-z]{6}" required>
Here's a stackoverflow question that gives more information.
As i can see, the problem isn't on validateDate but on validateWorkshop. If you try to submit a blank form, without choosing a workshop, reason.length gets value 5. But if you pick a workshop, reason.length gets 13.
Not that i recomend your validation but to get this working, i just added a var error = ""; at the begining of validateWorkshop.
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
var error = "";
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
On the 82 line of my JavaScript I have "document.getElementById("errors").innerHTML = errMsg;" this code and I was wondering how to implement it into my HTML page so when the validation isn't correct the error message will be displayed in the correct place such as when someone is younger then 15 the error message will be displayed next to date of birth. At the moment I have my errors appearing in an alert but I'd like them to appear on the web page. I also when to know if my "storeForm" and "prefillForm" functions are correct because I tried to test them and it doesn't seem to work. How do I go about fixing these?
"use strict";
/*get variables from form and check rules*/
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
//var JobID = document.getElementById("JobID").value;
var firstName = document.getElementById("firstName").value;
var familyName = document.getElementById("familyName").value;
var midName = document.getElementById("midName").value;
var male = document.getElementById("male").checked;
var female = document.getElementById("female").checked;
var street = document.getElementById("street").value;
var suburb = document.getElementById("suburb").value;
var state = document.getElementById("state").options[document.getElementById("state").selectedIndex].text;
var postcode = document.getElementById("postcode").value;
var email = document.getElementById("email").value;
var number = document.getElementById("number").value;
var XML = document.getElementById("XML").checked;
var Java = document.getElementById("Java").checked;
var Python = document.getElementById("Python").checked;
var SQL = document.getElementById("SQL").checked;
var PERL = document.getElementById("PERL").checked;
var MySQL = document.getElementById("MySQL").checked;
var Windows = document.getElementById("Windows").checked;
var UNIX = document.getElementById("UNIX").checked;
var Linux = document.getElementById("Linux").checked;
var other = document.getElementById("other").checked;
var otherText = document.getElementById("otherText").value;
var dob = document.getElementById("dob").value.split("/");
var date = new Date(dob[2], parseInt(dob[1]) - 1, dob[0]);
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
//get varibles from form and check rules here
// if something is wrong set result = false, and concatenate error message
if (age >= 80) { // Outside age ranges.
errMsg = errMsg + "You must be 80 or younger to apply for this job\n";
result = false;
}
if (age <= 15) { // Outside age ranges.
errMsg = errMsg + "You must be 15 or older to apply for this job\n";
result = false;
}
if (!(postcode.charAt(0) == 3 || postcode.charAt(0) == 8) && state == "VIC") {
errMsg = errMsg + "Your state and postcode do not match. State VIC postcodes must start with a 3 or 8\n";
result = false;
} else if (!(postcode.charAt(0) == 1 || postcode.charAt(0) == 2) && state == "NSW") {
errMsg = errMsg + "Your state and postcode do not match. State NSW postcodes must start with a 1 or 2\n";
result = false;
} else if (!(postcode.charAt(0) == 4 || postcode.charAt(0) == 9) && state == "QLD") {
errMsg = errMsg + "Your state and postcode do not match. State QLD postcodes must start with a 4 or 9\n";
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "NT") {
errMsg = errMsg + "Your state and postcode do not match. State NT postcodes must start with a 0\n";
result = false;
} else if (!(postcode.charAt(0) == 6) && state == "WA") {
errMsg = errMsg + "Your state and postcode do not match. State WA postcodes must start with a 6\n";
result = false;
} else if (!(postcode.charAt(0) == 5) && state == "SA") {
errMsg = errMsg + "Your state and postcode do not match. State SA postcodes must start with a 5\n";
result = false;
} else if (!(postcode.charAt(0) == 7) && state == "TAS") {
errMsg = errMsg + "Your state and postcode do not match. State TAS postcodes must start with a 7\n";
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "ACT") {
errMsg = errMsg + "Your state and postcode do not match. State ACT postcodes must start with a 0\n";
result = false;
} else {
result = true;
}
if (other && document.getElementById("otherText").value.trim().length === 0) {
errMsg = errMsg + "You have selected other skills, you must enter one other skill in the text box\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
//document.getElementById("errors").innerHTML = errMsg;
}
if (result == true) {
storeForm(firstName, familyName, midName, dob, male, female, street, suburb, state, postcode, email, number, XML, Java, Python, SQL, PERL, MySQL, Windows, UNIX, Linux, other, otherText)
}
return result; //if false the information will not be sent to the server
}
function storeForm(firstName, familyName, midName, dob, male, female, street, suburb, state, postcode, email, number, XML, Java, Python, SQL, PERL, MySQL, Windows, UNIX, Linux, other, otherText) {
//get values and assign them to sessionStorage attribute.
//we use the same name for the attrubute and the element id to avoid confustion
sessionStorage.firstName = firstName;
sessionStorage.familyName = familyName;
sessionStorage.midName = midName;
sessionStorage.dob = dob;
sessionStorage.male = male;
sessionStorage.female = female;
sessionStorage.street = street;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = postcode;
sessionStorage.email = email;
sessionStorage.number = number;
sessionStorage.XML = XML;
sessionStorage.Java = Java;
sessionStorage.Python = Python;
sessionStorage.SQL = SQL;
sessionStorage.PERL = PERL;
sessionStorage.MySQL = MySQL;
sessionStorage.Windows = Windows;
sessionStorage.UNIX = UNIX;
sessionStorage.Linux = Linux;
sessionStorage.other = other;
sessionStorage.otherText = otherText;
}
/* check if session day on user exists and if so prefill the form*/
function prefillForm() {
if (sessionStorage.firstName != undefined) {
document.getElementById("firstName").value = sessionStorage.firstName;
document.getElementById("familyName").value = sessionStorage.familyName;
document.getElementById("midName").value = sessionStorage.midName;
document.getElementById("dob").value = sessionStorage.dob;
if (sessionStorage.male == ("true")) {
document.getElementById("male").checked = true;
}
if (sessionStorage.female == ("true")) {
document.getElementById("female").checked = true;
}
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("number").value = sessionStorage.number;
if (sessionStorage.XML == ("true")) {
document.getElementById("XML").checked = true;
}
if (sessionStorage.Java == ("true")) {
document.getElementById("Java").checked = true;
}
if (sessionStorage.Python == ("true")) {
document.getElementById("Python").checked = true;
}
if (sessionStorage.SQL == ("true")) {
document.getElementById("SQL").checked = true;
}
if (sessionStorage.PERL == ("true")) {
document.getElementById("PERL").checked = true;
}
if (sessionStorage.MySQL == ("true")) {
document.getElementById("MySQL").checked = true;
}
if (sessionStorage.Windows == ("true")) {
document.getElementById("Windows").checked = true;
}
if (sessionStorage.UNIX == ("true")) {
document.getElementById("UNIX").checked = true;
}
if (sessionStorage.Linux == ("true")) {
document.getElementById("Linux").checked = true;
}
if (sessionStorage.other == ("true")) {
document.getElementById("other").checked = sessionStorage.other;
}
document.getElementById("otherText").value = sessionStorage.otherText;
}
}
function referenceNum1() {
//this function defines the local storage for the first job
localStorage.JobID = "QM593";
}
function referenceNum2() {
//this function defines the local storage for the second job;
localStorage.JobID = "CS197";
}
function init() {
var path = window.location.pathname;
var page = path.split("/").pop();
if (page == "apply.html") {
var regForm = document.getElementById("regform"); // get ref to the HTML element
window.onload = prefillForm();
regForm.onsubmit = validate; //register the event listener
//this puts the job id into the field
document.getElementById("JobID").value = localStorage.JobID;
} else {
//this makes it so that the 2 different functions run when the hyperlinks are clicked
var job1 = document.getElementById("job1");
var job2 = document.getElementById("job2");
var JobID
job1.onclick = referenceNum1;
job2.onclick = referenceNum2;
}
}
window.onload = init;
<article>
<header>
<h1>The Virtual World</h1>
<nav>
<p class="menu">Home</p>
<p class="menu">Jobs</p>
<p class="menu">Apply</p>
<p class="menu">About</p>
<p class="menu">Enhancements</p>
</nav>
</header>
<section id="required">
<h5>All fields with * are required</h5>
</section>
<form id="regform" method="post" action="http://mercury.swin.edu.au/it000000/formtest.php">
<fieldset>
<legend>Job Application</legend>
<p><label for="JobID">*Job ID:</label>
<input type="text" name="JobID" id="JobID" maxlength="5" size="10" pattern="^[a-zA-Z]{2}[0-9]{3}$" required="required" /></p>
<section id="choose">
<h5>Please choose from QM593 or CS197</h5>
</section>
<fieldset>
<legend>Personal Details</legend>
<p><label for="title">*Title:</label>
<select name="title" id="title" required="required">
<option value="">Please Select</option>
<option value="title">Dr</option>
<option value="title">Mr</option>
<option value="title">Miss</option>
<option value="title">Mrs</option>
<option value="title">Ms</option>
</select></p>
<p><label for="firstName">*First Name:</label>
<input type="text" name="firstName" id="firstName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" required="required" />
<label for="familyName">*Family Name:</label>
<input type="text" name="familyName" id="familyName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" required="required" /></p>
<p><label for="midName">Middle Name:</label>
<input type="text" name="midName" id="midName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" /></p>
<p><label for="dob">*Date of Birth:</label>
<input type="text" name="dob" id="dob" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" maxlength="10" size="10" required="required" /></p>
<p>*Gender:
<label for="male">Male</label>
<input type="radio" id="male" name="sex" value="male" required="required" />
<label for="female">Female</label>
<input type="radio" id="female" name="sex" value="female" required="required" /></p>
<p><label for="street">*Street Address:</label>
<input type="text" name="street" id="street" maxlength="40" size="30" required="required" /></p>
<p><label for="suburb">*Suburb/town:</label>
<input type="text" name="suburb" id="suburb" maxlength="40" size="20" required="required" /></p>
<p><label for="state">*State:</label>
<select name="state" id="state" required="required">
<option value="">Please Select</option>
<option value="state">VIC</option>
<option value="state">NSW</option>
<option value="state">QLD</option>
<option value="state">NT</option>
<option value="state">WA</option>
<option value="state">SA</option>
<option value="state">TAS</option>
<option value="state">ACT</option>
</select></p>
<p><label for="postcode">*Postcode:</label>
<input type="text" name="postcode" id="postcode" minlength="4" maxlength="4" size="10" pattern="^[0-9]{4}$" required="required" /></p>
<p><label for="email">*Email:</label>
<input type="email" name="email" id="email" size="30" required="required" /></p>
<p><label for="number">*Phone number:</label>
<input type="tel" name="number" id="number" minlength="8" maxlength="12" size="10" required="required" /></p>
<p>Skill list:</p>
<p><label for="C/C+">C/C+</label>
<input type="checkbox" id="C/C+" name="category[]" checked="checked" /></p>
<p><label for="XML">XML</label>
<input type="checkbox" id="XML" name="category[]" /></p>
<p><label for="Java">Java</label>
<input type="checkbox" id="Java" name="category[]" /></p>
<p><label for="Python">Python</label>
<input type="checkbox" id="Python" name="category[]" /></p>
<p><label for="SQL">SQL</label>
<input type="checkbox" id="SQL" name="category[]" /></p>
<p><label for="PERL">PERL</label>
<input type="checkbox" id="PERL" name="category[]" /></p>
<p><label for="MySQL">MySQL</label>
<input type="checkbox" id="MySQL" name="category[]" /></p>
<p><label for="Windows">Windows</label>
<input type="checkbox" id="Windows" name="category[]" /></p>
<p><label for="UNIX">UNIX</label>
<input type="checkbox" id="UNIX" name="category[]" /></p>
<p><label for="Linux">Linux</label>
<input type="checkbox" id="Linux" name="category[]" /></p>
<p><label for="other">Other Skills:</label>
<input type="checkbox" id="other" name="category[]" /></p>
<textarea id="otherText" name="other" rows="8" cols="70" placeholder="Please write any other skills you may have here..."></textarea>
</p>
</fieldset>
</fieldset>
<input type="submit" value="Apply" />
<input type="reset" value="Reset Application" />
</form>
</article>
you may create a generic function like that :
function show_error(element, message) {
element.parentElement.innerHTML += "<span class='error'>" + message + "</span>";
}
//call the function
show_error(document.getElementById('street'), 'error message');
.error {
color: red;
}
<p><label for="street">*Street Address:</label>
<input type="text" name="street" id="street" maxlength="40" size="30" required="required" /></p>
<p><label for="suburb">*Suburb/town:</label>
<input type="text" name="suburb" id="suburb" maxlength="40" size="20" required="required" /></p>
Then you can add another function to remove this error.
You can do the below to update when there is an error. I have added a small code to demonstrate.
$(document).ready(function() {
$("#btn").click(function() {
validate();
});
});
function validate() {
var errMsg = "";
var date = new Date($('#dpDoB').val());
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
if (age >= 80) { // Outside age ranges.
errMsg = errMsg + "You must be 80 or younger to apply for this job\n";
$("#dob").append("<span>" + errMsg + "</span>");
result = false;
}
if (age <= 15) { // Outside age ranges.
errMsg = errMsg + "You must be 15 or older to apply for this job\n";
$("#dob").append("<span>" + errMsg + "</span>");
result = false;
}
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<div id="form">
<div id="dob">
<input id="dpDoB" type="date" />
</div>
<div>
<input type="button" id="btn" class="btn btn-default" value="click me">
</div>
</div>
I am trying to make an order form that validates all entries to make sure the text boxes have data, and that the one of the 3 radio buttons is selected. As you can see in my code, I used a function to validate all the text boxes that are required, but I can not get the radio buttons to validate. I have tried if else statements and loops, but none of them have worked for me. I have tried including the radio button validation in the current function, and also tried making a new function just for it. Please help!
HTML here:
<form action="FormProcessor.html.html" method="get" onsubmit="return check();">
<select>
<option>Hand Tool</option>
<option>Saw</option>
<option>Hammer</option>
<option>Screwdriver</option>
<option>Wrench</option>
<option>Pliers</option>
</select>
<select>
<option>Power Tools</option>
<option>Circular Saw</option>
<option>Sabre Saw</option>
<option>Drill</option>
<option>Belt Sander</option>
<option>Table Saw</option>
</select>
<label>
<select>
<option>Materials</option>
<option>Plywood</option>
<option>Shingles</option>
<option>Nails</option>
<option>Screws</option>
</select>
</label>
<label>First Name
<input type="text" id="firstname" name="firstname" placeholder="First Name"></label>
<label>Last Name
<input type="text" id="lastname" name="lastname" placeholder="Last Name"></label> <br><br>
<label>Street Address 1
<input type="text" id="street_address_1" name="street_address_1" placeholder="Address 1"></label> <br><br>
<label>Street Address 2
<input type="text" id="street_address_2" name="street_address_2" placeholder="Address 2"></label> <br><br>
<label>City
<input type="text" id="city" name="city" placeholder="City"></label>
<label>State
<input type="text" id="state" name="State" placeholder="State"></label>
<label>Zip
<input type="text" id="zip_code" name="zip_code" placeholder="Zip"></label> <br><br>
<label>Phone
<input type="text" id="phone" name="phone" placeholder="Phone"></label>
<label>Fax
<input type="text" id="fax" name="fax" placeholder="Fax"></label> <br><br>
<label>Payment Method?
<input type="radio" name="card_type" id="visa">
<label for="visa">Visa</label>
<input type="radio" name="card_type" id="mastercard">
<label for="mastercard">MasterCard</label>
<input type="radio" name="card_type" id="americanexpress">
<label for="americanexpress">American Express</label><br><br>
<label>Credit Card Number
<input type="text" id="credit_card_number" name="credit_card_number" placeholder="Credit Card Number"></label> <br><br>
<label>Experiation Month
<select id = month>
<option>Month</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
</label>
<label>Experiation Year
<select id = year>
<option>Year</option>
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select> <br>
</label> <br><br>
<input type="submit" value="Submit Order">
JS Here
function check() {
var errormessage = "";
if (document.getElementById('firstname').value == "") {
errormessage += 'Please enter a First Name \n';
}
if (document.getElementById('lastname').value == "") {
errormessage += 'Please enter a Last Name \n';
}
if (document.getElementById('street_address_1').value == "") {
errormessage += 'Please enter your Street Address \n';
}
if (document.getElementById('city').value == "") {
errormessage += 'Please enter a City \n';
}
if (document.getElementById('state').value == "") {
errormessage += 'Please enter a State \n';
}
if (document.getElementById('zip_code').value == "") {
errormessage += 'Please enter a Zip Code \n';
}
if (document.getElementById('phone').value == "") {
errormessage +='Please enter a Phone Number \n';
}
if (document.getElementById('credit_card_number').value == "") {
errormessage += 'Please enter a Credit Card \n';
}
if (document.getElementById('month').value == "") {
errormessage += 'Please enter a Month \n';
}
if (document.getElementById('year').value == "") {
errormessage += 'Please enter a Year \n';
}
if (errormessage != "") {
alert(errormessage);
return false;
}
}
How about setting up a function to validate a radio button, something like this:
function validateRadio(radioGroup) {
for (i = 0; i < radioGroup.length; ++ i) {
if (radioGroup[i].checked) return true;
}
return false;
}
And then in your check() function you can call the validateRadio() function and pass it the radio group you want to check:
if(!validateRadio(document.forms["formid"]["card_type"])) {
errormessage +='Please select a Payment Method\n';
}