Javascript form summary page - javascript

I have created a Javascript form with multiple functions, and I want to generate a summary page of all the values entered in the form after the submit button has been clicked. My question is how do I generate this summary page? (Please see my code below)
Thanks
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var addr = document.getElementById('addr');
var pcode = document.getElementById('pcode');
var course = document.getElementById('course');
var username = document.getElementById('username');
var email = document.getElementById('email');
// Check each input in the order that it appears in the form!
if(isAlphabet(firstname, "Please enter only letters for your name")){
if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
if(isNumeric(pcode, "Please enter a valid post code")){
if(madeSelection(course, "Please Choose a Course")){
if(lengthRestriction(username, 6, 8)){
if(emailValidator(email, "Please enter a valid email address")){
return true;
}
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}
function madeSelection(elem, helperMsg){
if(elem.value == "Please Choose a Course"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<form name="javaform" action="javasummary.html" method="post" onsubmit="return formValidator();">
<label>First Name:</label> <input type='text' id='firstname' size='50'/><br />
<label>Last Name:</label> <input type='text' id='lastname' size='50'/><br />
<label>Address:</label> <input type='text' id='addr' size='50' /><br />
<label>Post Code:</label> <input type='text' id='pcode' size='50'/><br />
<label>Course:</label> <select id='course'>
<option>Please Choose a Course</option>
<option>PHP | £500 | 18/02/2012</option>
<option>CSS | £400 | 03/03/2011</option>
<option>HTML | £550 | 04/02/2012</option>
<option>FLASH(NEW) | £1220 | 25/12/2012</option>
</select><br />
<label>Username(6-8 characters):</label>
<input type='text' id='username' size='50'/><br />
<label>Email:</label>
<input type='text' id='email' size='50'/><br />
<input type='submit' value='Submit'>
</form>

Related

How can I prevent my form from being submitted?

I want the form to not be submitted when the inputs are wrong. The error messages do appear but my form still gets submitted nonetheless. I cant seem to find the problem would appreciate the help thank you :)-----------------------------------------------------------------------------------------------------
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading" >First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
fname.style.color="red";
return false;
} else {
fname.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false)
{
errorC.innerHTML = "Wrong format";
mcode.style.color="red";
return false;
} else {
mcode.innerHTML = "";
}
return true; }
The problem seems to be these four lines of code:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
fname and mname are strings, therfore fname.style and mname.style both result in undefined. Obviously you can't set properties on undefined which is why you are getting an error.
//You are getting the value properties which are strings:
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
The error is stopping your code before you can return false, preventing the cancelation of the form submit.
The solution is to instead make two more variables storing the actual input elements:
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
Then change lines:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
to:
finput.style.color="red";
finput.innerHTML = "";
minput.style.color="red";
minput.innerHTML = "";
Here is a working version:
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading">First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
finput.style.color = "red";
return false;
} else {
finput.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false) {
errorC.innerHTML = "Wrong format";
minput.style.color = "red";
return false;
} else {
minput.innerHTML = "";
}
return true;
}
</script>
Pass the event to the form validation function
onsubmit="return validateForm(e)"
Then prevent default submission using
e.preventDefault();
Your return statement should be inside a condition. Right now you're existing the condition and ending the function with a return true; regardless of what the conditional statements have already returned. So:
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}else{
return true; // THIS IS WHERE YOU NEED TO RETURN TRUE
}
I see you're returning false in multiple if statements. You'll need to find a way to unify the conditions so that you have one return only for for either true or false.

JavaScript form validation- Date

My school gave me a week to learn JavaScript. We started with form validation.
I was able to successfully figure out name and email address but I am unable to add the date validation that is required.
My code so far:
function formValidator() {
// Make quick references to our fields
var name = document.getElementById('name');
var email = document.getElementById('email');
// Check each input in the order that it appears in the form!
if (isAlphabet(name, "Please enter only letters for your name")) {
if (emailValidator(email, "Please enter a valid email address")) {
return true;
}
}
return false;
}
function notEmpty(elem, helperMsg) {
if (elem.value.length == 0) {
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isNumeric(elem, helperMsg) {
var numericExpression = /^[0-9]+$/;
if (elem.value.match(numericExpression)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphabet(elem, helperMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (elem.value.match(alphaExp)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, helperMsg) {
var alphaExp = /^[0-9a-zA-Z]+$/;
if (elem.value.match(alphaExp)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
function lengthRestriction(elem, min, max) {
var uInput = elem.value;
if (uInput.length >= min && uInput.length <= max) {
return true;
} else {
alert("Please enter between " + min + " and " + max + " characters");
elem.focus();
return false;
}
}
function madeSelection(elem, helperMsg) {
if (elem.value == "Please Choose") {
alert(helperMsg);
elem.focus();
return false;
} else {
return true;
}
}
function emailValidator(elem, helperMsg) {
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if (elem.value.match(emailExp)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
//javascriptkit.com/script/script2/validatedate.shtml
function checkdate(input) {
var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval = false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else { //Detailed check for valid date ranges
var monthfield = input.value.split("/")[0]
var dayfield = input.value.split("/")[1]
var yearfield = input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield - 1, dayfield)
if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval = true
}
if (returnval == false) input.select()
return returnval
}
<div id="form">
<h1>Questions? Contact Us!</h1>
<form onsubmit='return formValidator()'>
<label for="name">Name:</label>
<input type='text' id='name' /><br />
<label for="email">Email:</label>
<input type='text' id='email' /><br />
<label for="date">Date: </label>
<input type="text" id="date" required /> <br>
<label for="message">Question:</label>
<textarea name="message" rows="8" cols="20" required>Please make sure your question is at least five words.</textarea> <br>
<input type='submit' value='Check Form' />
</form>
</div>
I think I should change the function check date but I'm not sure what to do.
Thanks.
Wire up the date validation in your function.formValidator - I modified that function to use an isValid to avoid large numbers of nested validation.
IF you want to ONLY work with one at a time, starting with name you could use that in the next as well by adding it to the start of each one, it skips if it is false:
if (isValid && !emailValidator(email, "Please enter a valid email address"))
Note the added ! on !emailValidator says to make isValid false if it fails.
function formValidator() {
// Make quick references to our fields
var name = document.getElementById('name');
var email = document.getElementById('email');
var mydate = document.getElementById('date'); // add this one
var isValid = true; //added this (form level valid true/false)
// Check each input in the order that it appears in the form!
if (!isAlphabet(name, "Please enter only letters for your name")) {
isValid = false;
}
if (!emailValidator(email, "Please enter a valid email address")) {
isValid = false;
}
// check the date
if (!checkdate(mydate)) {
isValid = false;
alert("bad date " + mydate.value);
}
return isValid;
}
function notEmpty(elem, helperMsg) {
if (elem.value.length == 0) {
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isNumeric(elem, helperMsg) {
var numericExpression = /^[0-9]+$/;
if (elem.value.match(numericExpression)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphabet(elem, helperMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (elem.value.match(alphaExp)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, helperMsg) {
var alphaExp = /^[0-9a-zA-Z]+$/;
if (elem.value.match(alphaExp)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
function lengthRestriction(elem, min, max) {
var uInput = elem.value;
if (uInput.length >= min && uInput.length <= max) {
return true;
} else {
alert("Please enter between " + min + " and " + max + " characters");
elem.focus();
return false;
}
}
function madeSelection(elem, helperMsg) {
if (elem.value == "Please Choose") {
alert(helperMsg);
elem.focus();
return false;
} else {
return true;
}
}
function emailValidator(elem, helperMsg) {
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if (elem.value.match(emailExp)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
//javascriptkit.com/script/script2/validatedate.shtml
function checkdate(input) {
var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval = false;
if (!validformat.test(input.value)) {
alert("Invalid Date Format. Please correct and submit again.");
} else { //Detailed check for valid date ranges
var monthfield = input.value.split("/")[0];
var dayfield = input.value.split("/")[1];
var yearfield = input.value.split("/")[2];
var dayobj = new Date(yearfield, monthfield - 1, dayfield);
if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.");
} else {
returnval = true;
}
}
if (returnval == false) {
input.select();
}
return returnval;
}
<div id="form">
<h1>Questions? Contact Us!</h1>
<form onsubmit='return formValidator()'>
<label for="name">Name:</label>
<input type='text' id='name' /><br />
<label for="email">Email:</label>
<input type='text' id='email' /><br />
<label for="date">Date: </label>
<input type="text" id="date" required /> <br>
<label for="message">Question:</label>
<textarea name="message" rows="8" cols="20" required>Please make sure your question is at least five words.</textarea> <br>
<input type='submit' value='Check Form' />
</form>
</div>

No alert message after user inputs correct validation (javascript)

After the user enters into the field and press "check form" there is suppose to be a popout helper message alerting the user instead it just goes to the next page.
What is wrong in the code that it doesn't show any alert message after the user validates?
I'm trying to make it in such a way that each field gets an alert after validating
function formValidation() {
var firstname = document.getElementById('firstname');
var zip = document.getElementById('zip');
var state = document.getElementById('state');
var username = document.getElementById('username');
var email = document.getElementById('email');
if(isAlphabet(firstname, "Please enter only letters for first name")){
if(isNumeric(zip, "Please enter only a valid zip code")){
if(madeSelection(state, "Please choose a state")){
if(lengthRestriction(username, 6, 8)){
if(emailValidator(email, "Please enter a valid email address.")){
alert("The following information has been entered: \n"+document.getElementById('firstname').value);
return true;
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus();
return false;
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <=max){
return true;
}else{
alert("Please enter between " +min+" and " +max+" characters");
elem.focus();
return false;
}
}
function madeSelection(elem, helperMsg){
if(elem.value == "Please Choose"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
<form onsubmit='return formValidator()' action="Lab17b.html" method="get">
First Name: <input type='text' id='firstname' name='first' /><br />
Zip Code: <input type='text' id='zip' name='zip'/><br />
State: <select id='state' name='state'>
<option>Please Choose</option>
<option>AL</option>
<option>TX</option>
<option>CA</option>
<option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' name='username' /><br />
Email: <input type='text' id='email' name='email'/><br />
<input type='submit' value='Check Form' />
</form>
You have given wrong function name in onsubmit method
<form onsubmit='return formValidation()' action="Lab17b.html" method="get">
Fiddle -- https://jsfiddle.net/knmajLeg/
As RahulB said, your function name was wrong:
formValidator vs formValidation
By the way, if you're interested, here your code in an other way.
Remember: your code needs to be clean/logical/semantical to debug it without effort.
Every time you repeat a bunch of code, try to make a method.
function formValidator() {
// Notice how we can see/understand the logical of
// the function
let informationAreValid =
firstNameIsValid() &&
zipIsValid() &&
stateIsValid() &&
userNameIsValid() &&
mailIsValid()
if ( informationAreValid )
{
alert("The following information has been entered: \n"+document.getElementById('firstname').value);
}
return informationAreValid ;
}
// The core of the validation
//
// #param {String} type Type of validation ('notEmpty', etc.)
// #param {DOMElement} elem The field
// #param {AnyValue} expected The value expected, if any
function isConform(type, elem, expected) {
let value = elem.value ;
switch ( type )
{
case 'notEmpty':
return value.length > 0;
case 'isNumeric':
return value.match(/^[0-9]+$/);
case 'isAlphabet':
return value.match(/^[a-zA-Z]+$/);
case 'isAlphaNum':
return value.match(/^[0-9a-zA-Z]+$/);
case 'isNotEqual':
return value != expected ;
case 'isEqual':
return value === expected ;
case 'isMailValid':
return value.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/);
case 'isBetween':
value = value.length ;
return value >= expected[0] && value <= expected[1]
}
}
// The checker
//
// We validate the values, send a alert message if information
// is bad and focus in the field.
//
// #return true if value of Dom element with id +idElem+
// match against the +typeValidation+ and the +expected+
// value if any.
// Otherwise, display an alert message and return false
//
function check(typeValidation, idElem, expected, errorMsg ){
let elem = document.getElementById( idElem ) ;
if ( isConform(typeValidation, elem, expected) ) { return true }
switch ( typeValidation ) {
case 'isBetween':
let [min, max] = expected ;
errorMsg = eval('`'+errorMsg+'`') ;
}
alert(errorMsg);
elem.focus() ;
return false ;
}
// Check method of every form field
//
// Here's is defined the error messages
function firstNameIsValid() {
let res = check('notEmpty', 'firstname', null, "First name is required") ;
if ( ! res ) { return false }
return check('isAlphabet', 'firstname', "Please enter only letters for first name");
}
function zipIsValid(){
return check('isNumeric', 'zip', null, "Please enter only a valid zip code") ;
}
function stateIsValid()
{
return check('isNotEqual', 'state', "Please Choose", "Please choose a state") ;
}
function mailIsValid()
{
return check('isMailValid', 'email', null, "Please enter a valid email address") ;
}
function userNameIsValid()
{
return check('isBetween', 'username', [6, 8], "Please enter between ${min} and ${max} characters") ;
}
<form onsubmit='return formValidator()' action="" method="get">
First Name: <input type='text' id='firstname' name='first' /><br />
Zip Code: <input type='text' id='zip' name='zip'/><br />
State: <select id='state' name='state'>
<option>Please Choose</option>
<option>AL</option>
<option>TX</option>
<option>CA</option>
<option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' name='username' /><br />
Email: <input type='text' id='email' name='email'/><br />
<input type='submit' value='Check Form' />
</form>

Javascript code won't work on my form [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am working on a form but my form is not working whenever I press submit. I am trying to evaluate whether sections of the form is empty, the email, and the number of digits for a user id. When I press submit nothing happens and I have been stuck like this for a while. FYI I have to use plain js and html.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Student Login Form</title>
<link rel='stylesheet' href='studentform.css' type='text/css' />
<script src="studentform.js"></script>
</head>
<body onload="document.form.studentid.focus();">
<h1>Student Login</h1>
<div class="container">
<form name="form" onsubmit="return validate();">
<label for="studentid">Student ID:</label>
<input type="number" name="studentid" maxlength="8" id="studentid" required />
<label for="name">Name:</label>
<input type="text" name="name" size="50" id="name" required />
<label for="email">Email:</label>
<input type="email" name="email" size="50" id="email" required />
<label for="emailconfirm">Email Confirmation:</label>
<input type="checkbox" name="emailconfirm" checked /><span>Send an email confirmation</span>
<select>
<option selected>Student Registration</option>
<option>Transcript</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
`
Js.
function validate(){
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(nameEmpty(name))
{
if(studentidEmpty(studentid))
{
if(emailEmpty(email))
{
if(digitCheck(studentid))
{
if checkEmail(email)
{
verify(name, studentid)
}
}
}
}
}
return false;
}
function studentidEmpty(studentid){
if ( studentid == "" ){
alert("Please provide your student id!");
studentid.focus();
return false;
}
}
function nameEmpty(name){
if ( name == "" ){
alert("Please provide your name!");
name.focus() ;
return false;
}
}
function emailEmpty(email){
if( email == "" ){
alert( "Please provide your email!" );
email.focus();
return false;
}
function digitCheck(studentid){
var ok = studentid.search(".{8,}");
if (ok!=0){
alert("Please provide ID with 8 digits.");
return false;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
function verify(name, studentid){
var personList = [["Joe",11111111],["Tammy",22222222],["Jones",33333333]];
for (list in personList) {
if (name in list && studentid in list){
alert("Welcome! An email verification with be sent soon.");
return true;
} else{
alert("Student Name and/or ID not found in records");
return false;
}
}
}
}
I think you should fix this line:
if checkEmail(email)
to
if (checkEmail(email))
you have forgotten the parentheses.
Edit:
I have completely fixed your code. Your errors:
you have forgotten to add else clauses for your field checkers, they were only returning false if the validation failed
your checking "if array contains value" was wrong, I have added a method from here
you were trying to focus on the values, not tags
you were trying to test email value from the "value of the value" not "value"
function validate() {
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (nameEmpty(name)) {
if (studentidEmpty(studentid)) {
if (emailEmpty(email)) {
if (digitCheck(studentid)) {
if (checkEmail(email)) {
return verify(name, studentid);
}
}
}
}
}
return false;
}
function studentidEmpty(studentid) {
if (studentid == "") {
alert("Please provide your student id!");
document.getElementById("studentid").focus();
return false;
} else {
return true;
}
}
function nameEmpty(name) {
if (name == "") {
alert("Please provide your name!");
document.getElementById("name").focus();
return false;
} else {
return true;
}
}
function emailEmpty(email) {
if (email == "") {
alert("Please provide your email!");
document.getElementById("email").focus();
return false;
} else {
return true;
}
}
function digitCheck(studentid) {
var ok = studentid.search(".{8,}");
if (ok != 0) {
alert("Please provide ID with 8 digits.");
return false;
} else {
return true;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
return false;
} else {
return true;
}
}
function verify(name, studentid) {
var personList = [
["Joe", 11111111],
["Tammy", 22222222],
["Jones", 33333333]
];
for (list in personList) {
if (contains.call(list, name) && contains.call(list, studentid)) {
alert("Welcome! An email verification with be sent soon.");
return true;
}
}
alert("Student Name and/or ID not found in records");
return false;
}
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
<div>
<form>
<label for="name">Name:</label>
<input type="text" name="name" size="50" id="name" required />
<label for="studentid">Student ID:</label>
<input type="number" name="studentid" maxlength="8" id="studentid" required />
<label for="email">Email:</label>
<input type="email" name="email" size="50" id="email" required />
<label for="emailconfirm">Email Confirmation:</label>
<input type="checkbox" name="emailconfirm" checked /><span>Send an email confirmation</span>
<select>
<option selected>Student Registration</option>
<option>Transcript</option>
</select>
<input onclick="return validate();" type="submit" name="submit" value="Submit" />
</form>
</div>
Validate function always return false !! It shouldn't.
function validate(){
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
return nameEmpty(name) && studentidEmpty(studentid) && emailEmpty(email) && digitCheck(studentid) && checkEmail(email) && verify(name, studentid);
}
Then be sure your form looks like :
<form name="form" onsubmit="return validate();" action="javascript:void(0)">
</form>
And your autofocus input to look like :
<input type="number" name="studentid" maxlength="8" id="studentid" required autofocus/>
You're forgetting the parentheses.
It is also wrong to start and end each function, try using the code below with these corrections.
function validate() {
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (nameEmpty(name)) {
if (studentidEmpty(studentid)) {
if (emailEmpty(email)) {
if (digitCheck(studentid)) {
if (checkEmail(email)) {
verify(name, studentid)
}
}
}
}
}
return false;
}
function studentidEmpty(studentid) {
if (studentid == "") {
alert("Please provide your student id!");
studentid.focus();
return false;
}
}
function nameEmpty(name) {
if (name == "") {
alert("Please provide your name!");
name.focus();
return false;
}
}
function emailEmpty(email) {
if (email == "") {
alert("Please provide your email!");
email.focus();
return false;
}
}
function digitCheck(studentid) {
var ok = studentid.search(".{8,}");
if (ok != 0) {
alert("Please provide ID with 8 digits.");
return false;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
function verify(name, studentid) {
var personList = [
["Joe", 11111111],
["Tammy", 22222222],
["Jones", 33333333]
];
for (list in personList) {
if (name in list && studentid in list) {
alert("Welcome! An email verification with be sent soon.");
return true;
} else {
alert("Student Name and/or ID not found in records");
return false;
}
}
}

Javascript stopping form from passing data

resolved my javascript issue. Sorry it was mainly my fault as i copied and pasted my code instead of rewriting it out again. Strange thing is that it doesn't seem to pass the variables from the form to the process page as i have echo'd the SQL statement back out. This form did work previously to the java script all i added in was Post Code: for each row and even after deleting the javascript it still doesn't work :S
Sorry deadline tomorrow and im panicing.
<script type="text/javascript">
function checkForm()
{
var username = document.getElementById('username').value;
if(username.length < 5)
{
alert("Username is to short");
return false;
}
else if (username.length<16)
{
alert("Username is to long");
return false;
}
var firstName = document.getElementById('firstName').value;
if(firstName.length <3)
{
alert("Forname is to short");
return false;
}
var lastName = document.getElementById('lastName').value;
if (lastName.length <3)
{
alert("Surname is to short");
return false;
}
var address = document.getElementById('address').value;
if (address.length <8)
{
alert("Address is to short");
return false;
}
var town = document.getElementById('town').value;
if (town.length <3)
{
alert ("Town is to short");
return false;
}
var postCode = document.getElementById('postCode').value;
if (postCode.length <6)
{
alert ("Invalid Post Code");
return false;
}
else if (postCode.length>8)
{
alert("Invalid Post Code");
return false;
}
var cardType = document.getElementById('cardType').value;
if (cardType.length <3)
{
alert ("Please enter a valid card type");
return false;
}
var password = document.getElementById('password').value;
if (password.length <6)
{
alert ("You password must be between 6-12 characters");
return false;
}
else if(password.length>12)
{
alert ("Your password must be between 6-12 characters");
return false;
}
else
{
return true;
}
}
function checkUsername()
{
var username = document.getElementById('username').value;
var element = document.getElementById('username1');
if(username.length < 5)
{
element.innerHTML = "Username is to short";
element.style.color = "red";
}
else if (username.length >16)
{
element.innerHTML = "Username is to long";
element.style.color = "red";
}
else
{
element.innerHTML = "Username";
element.style.color = "green";
}
}
function checkFname()
{
var firstName = document.getElementById('firstName').value;
var element = document.getElementById('firstname1');
if(firstName.length < 3)
{
element.innerHTML = "Forname is to short";
element.style.color = "red";
}
else
{
element.innerHTML = "Forname";
element.style.color = "green";
}
}
function checkLname()
{
var lastName = document.getElementById('lastName').value;
var element = document.getElementById('surname1');
if(lastName.length < 3)
{
element.innerHTML = "Surname is to short";
element.style.color = "red";
}
else
{
element.innerHTML = "Surname";
element.style.color = "green";
}
}
function checkAddress()
{
var address = document.getElementById('address').value;
var element = document.getElementById('address1');
if(address.length < 8)
{
element.innerHTML = "Address is to short";
element.style.color = "red";
}
else
{
element.innerHTML = "Address";
element.style.color = "green";
}
}
function checkTown()
{
var town = document.getElementById('town').value;
var element = document.getElementById('town1');
if(town.length < 3)
{
element.innerHTML = "Town is to short";
element.style.color = "red";
}
else
{
element.innerHTML = "Town";
element.style.color = "green";
}
}
function checkPostCode()
{
var postCode = document.getElementById('postCode').value;
var element = document.getElementById('postcode1');
if(postCode.length < 6)
{
element.innerHTML = "Post code is to short";
element.style.color = "red";
}
else if (postCode.length>8)
{
element.innerHTML = "Post Code To Long";
element.style.color = "red";
}
else
{
element.innerHTML = "Post Code";
element.style.color = "green";
}
}
function checkCard()
{
var cardType = document.getElementById('cardType').value;
var element = document.getElementById('card1');
if(cardType.length < 3)
{
element.innerHTML = "Card is to short";
element.style.color = "red";
}
else
{
element.innerHTML = "Card Type";
element.style.color = "green";
}
}
function checkPassword()
{
var password = document.getElementById('password').value;
var element = document.getElementById('password1');
if(password.length < 6)
{
element.innerHTML = "Password is to short";
element.style.color = "red";
}
else if (password.length>16)
{
element.innerHTML = "Password is to long";
element.style.color = "red";
}
else
{
element.innerHTML = "Password";
element.style.color = "green";
}
}
</script>
<p><b><h3>Welcome User Please Register</h3></b></p>
<form action="registerUserProcess.php" id="registerUserForm" method="post" name="registerUserForm" >
<table>
<tr><td><label id="username1">Username:</label></td><td><input id="username" type="text" size="16" onBlur='checkUsername();'/></td></tr>
<tr><td><label id="firstname1">Forename:</label></td><td><input id="firstName" type="text" size="20" onBlur="checkFname();" /></td></tr>
<tr><td><label id="surname1">Surname:</label></td><td><input id="lastName" type="text" size="30" onBlur="checkLname();" /></td></tr>
<tr><td><label id="address1">Address:</label></td><td><input id="address" type="text" size="50" onBlur="checkAddress();" /></td></tr>
<tr><td></td><td><input id="address2" type="text" size="50" onBlur="" /></td></tr>
<tr><td><label id="town1">Town:</label></td><td><input id="town" type="text" size="50" onBlur="checkTown();" /></td></tr>
<tr><td><label id="postcode1">Post Code:</label></td><td> <input type="text" id="postCode" size="8" onBlur="checkPostCode();" /></td></tr>
<tr><td><label id="contact1">Contact No:</label></td><td> <input type="number" id="contact" size="12" onBlur="checkContactNo();" /></td></tr>
<tr><td>Card Number:</td><td><input type="number" id="cardNo1" size="4" /> - <input type="number" id="cardNo2" size="4" /> - <input type="number" id="cardNo3" size="4" /> - <input type="number" id="cardNo4" size="4" /></td></tr>
<tr><td><label id="card1">Card Type</label></td><td> <input type="text" id="cardType" size="8" onBlur="checkCard();" /></td></tr>
<tr><td>Email Address:</td><td><input id="emailAddress" type="text" size="50" /></td></tr>
<tr><td><label id="password1">Password:</label></td><td><input id="password" type="password" size="16" onBlur="checkPassword();" /></td></tr>
<tr><td><label id="terms1">Accept Terms & Conditions:</label></td><td><input type="checkbox" id="termsConditions" value="yes" onBlur="checkTerms();" /></td></tr>
<tr><td><input type="reset" id="resetForm" value="Reset" id="resetForm" /></td><td><input type="submit" id="submitUser" value="Submit" id="submitUser" onSubmit='return checkForm();' /></td></tr>
</table>
</form>
As others said, check your syntax. In checkform(), it should be
else if (username.length > 16)) instead of < 16
and in checkUsername() you spelled length wrong.
But your main problem is in your returns. In checkform() you should only put return true at the end when everything has been validated, or else the function just exit after the first validation.
You could also refactor all of this. You've got plenty of function that do almost the same thing. If you make one function that take minimum characters, maximum characters and the control to validate in parameters, you could do all of your code in 20 to 30 lines.
Plus, it seems like you copy-pasted some of your functions without changing the name of the variables or the targeted control. In fact, you assign Username as a variable in every function, but change the name in the condition, meaning you use an unassign variable.
Function: checkForm():
You need to change the second else if to:
else if (username.length<16)) needs to be > 16.
--
Function: checkUsername():
You have incorrectly spelled length. Change it to:
else if (username.length>16)
This is too much code for one question, but I noticed a few things in the first function:
else if (username.length<16) // This should probably be username.length > 16
{
alert("Username is to long");
return false;
}
if (isNAN(contact)) // this should probably be !isNaN(contact)
{
return true;
}
You misspelled length in the following: username.lenght>16
This is the reason your too long isn't working.
function checkUsername()
{
var username = document.getElementById('username').value;
var element = document.getElementById('username1');
if(username.length < 5)
{
element.innerHTML = "Username is to short";
element.style.color = "red";
}
else if (username.lenght>16)
{
element.innerHTML = "Username is to long";
element.style.color = "red";
}
else
{
element.style.color = "green";
}
}

Categories