No alert message after user inputs correct validation (javascript) - 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>

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>

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 form summary page

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>

Javascript - Value not passing to function

So I have this form:
<form name="login" id="login" action="" method="POST" onSubmit="return test()">
<input type="text" size="10" name="username" /><div id="wrongUser"></div>
<br />
<input type="password" size="10" name="password" /><div id="wrongPass"></div>
<br />
<input type="submit" value="submit" name="submit" /><br /><br />
</form>
and these two functions:
function test()
{
var user = document.login.username.value;
var pass = document.login.password.value;
if((user == "" || user == null) && (pass == "" || pass == null))
{
document.getElementById('wrongUser').innerText = "Please Enter Username";
document.getElementById('wrongPass').innerText = "Please Enter Password";
return false;
}
if(checkEmpty(user, 'wrongUser', "Please Enter Username"))
return false
if(checkEmpty(pass, 'wrongPass', "Please Enter Password"))
return false;
return true;
}
function checkEmpty(name, id, output)
{
if(name == "" || name == null)
{
document.getElementById(id).innerText = "";
document.getElementById(id).innerText = output;
return true;
}
else
return false;
}
Now the functions kinda work but not how I would think. If the user only doesn't enter anything (first time) then they get the 2 errors. If the user enter just a username (second time) then the username error should disappear, but it doesn't. If I take it out of the function and replace the variables with their normal values then it works just fine. Why would it change when put in this function?
Put the document.getElementById().innerText = '' in the else, not in the if. Because you only reset the innerText when it's empty, but you would like to reset the tekst if it's not empty:
function checkEmpty( name, id, output ) {
var elem = document.getElementById(id); // it's faster to put the element in a var
if( name === undefined || name == '' name == null )
elem.innerText = output;
return true;
else
elem.innerText = '';
return false;
}

Categories