Error messages showing on next line - javascript

I have an error message that pops up at the top of my form when something is wrong but the errors stay on the same line. How do I make them go under each other or under the correct place on the web page? I have the below code on my html to display my error message at the moment. If needed I can show my html as well.
<p id="error"></p>
JavaScript:
"use strict";
/*get variables from form and check rules*/
function validate(){
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
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
//Validation for Date of birth
if (age >= 80){ // Checks if age is over 80
errMsg = errMsg + "You must be 80 or younger to apply for this job\n";
result = false;
}
if (age <= 15){ // Checks if age is under 15
errMsg = errMsg + "You must be 15 or older to apply for this job\n";
result = false;
}
//Validation for state and corresponding postcode
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;
}
//Validation of other skill so checks if other skill box is checked and if so will check textbox for text
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
document.getElementById("error").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
}

#evan
var err = [];
....
....
...
err.push('You have selected other skills, you must enter one other skill in the text box');
....
....
err.push('Your state and postcode do not match. State QLD postcodes
must start with a 4 or 9');
...
// NEW CODE
var ul = document.createElement('ul');
for(var i=0; i< err.length; i++){
var li = document.createElement('li');
li.innerHtml = err[i];
ul.appendChild(li);
}
....
...
var pError = document.getElementById("error");
pError.innerHtml = ul;
I have written this code on the fly .. to the editor here. but i am sure i have clear my point. any doubt post comment below.

I think the better code architecture would be as follows as it gives your more control keeping the sync with your exisiting design.
<ul id="error"></ul>
JavaScript:
"use strict";
/*get variables from form and check rules*/
function validate(){
var errMsgs = []; /* change error message to array */
var result = true; /* assumes no errors */
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
//Validation for Date of birth
if (age >= 80){ // Checks if age is over 80
errMsgs.push("You must be 80 or younger to apply for this job");
result = false;
}
if (age <= 15){ // Checks if age is under 15
errMsgs.push("You must be 15 or older to apply for this job");
result = false;
}
//Validation for state and corresponding postcode
if (!(postcode.charAt(0) == 3 || postcode.charAt(0) == 8) && state == "VIC") {
errMsgs.push("Your state and postcode do not match. State VIC postcodes must start with a 3 or 8");
result = false;
} else if (!(postcode.charAt(0) == 1 || postcode.charAt(0) == 2) && state == "NSW") {
errMsgs.push("Your state and postcode do not match. State NSW postcodes must start with a 1 or 2");
result = false;
} else if (!(postcode.charAt(0) == 4 || postcode.charAt(0) == 9) && state == "QLD") {
errMsgs.push("Your state and postcode do not match. State QLD postcodes must start with a 4 or 9");
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "NT") {
errMsgs.push("Your state and postcode do not match. State NT postcodes must start with a 0");
result = false;
} else if (!(postcode.charAt(0) == 6) && state == "WA") {
errMsgs.push("Your state and postcode do not match. State WA postcodes must start with a 6");
result = false;
} else if (!(postcode.charAt(0) == 5) && state == "SA") {
errMsgs.push("Your state and postcode do not match. State SA postcodes must start with a 5");
result = false;
} else if (!(postcode.charAt(0) == 7) && state == "TAS") {
errMsgs.push("Your state and postcode do not match. State TAS postcodes must start with a 7");
result = false;
} else if (!(postcode.charAt(0) == 0) && state == "ACT") {
errMsgs.push("Your state and postcode do not match. State ACT postcodes must start with a 0");
result = false;
} else {
result = true;
}
//Validation of other skill so checks if other skill box is checked and if so will check textbox for text
if (other && document.getElementById("otherText").value.trim().length===0) {
errMsgs.push("You have selected other skills, you must enter one other skill in the text box");
result = false;
}
if (errMsgs.length > 0) { //only display message box if there is something to show
document.getElementById("error").innerHTML = '<li>' + errMsgs.glue('</li><li>') + '</li>'; /* Apending the error messages as li*/
}
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
}

Related

JavaScript Form Validation not working using isNaN

I have changed my code and added the isNaN to make sure a credit card validation is checking that only numbers are entered, however it broke the code.
Note this is only a code snippet of the broken code.
Tried adding backets and moving around code.
var american = document.getElementById("americanInput").value;
var master = document.getElementById("masterInput").value;
var visa = document.getElementById("visaInput").value;
var email = document.getElementById("email").value;
var errMsg = document.getElementById("errMsg");
var postcode = document.getElementById("billingPostcode").value;
var address = document.getElementById("billingAddress").value;
var suburb = document.getElementById("billingSuburb").value;
} else if (master.length > 0 && master.length !== 16 && isNaN(master)||
visa.length > 0 && visa.length !== 16 && isNaN(visa)||
american.length > 0 && american.length !== 15 && isNaN(american)){
errMsg.innerHTML = "Please check your card details again";
return false;
} else if (postcode.length < 4 || (!postcode.match(/^[0-9]*$/))) {
errMsg.innerHTML = "Please enter a valid postcode";
return false;
} else if (suburb.length < 8 || address.length < 8) {
errMsg.innerHTML = "Please check your address, to confirm details"
return false;
}
The code should validate and give an error message.
Try the below code. I have used 'OR' condition with isNaN instead of 'AND' condition. I assume you are checking for the credit card value is not null/undefined in your code. If not you need to check to make sure the below code works.
var american = document.getElementById("americanInput").value;
var master = document.getElementById("masterInput").value;
var visa = document.getElementById("visaInput").value;
var email = document.getElementById("email").value;
var errMsg = document.getElementById("errMsg");
var postcode = document.getElementById("billingPostcode").value;
var address = document.getElementById("billingAddress").value;
var suburb = document.getElementById("billingSuburb").value;
if ((master.length > 0 && (master.length !== 16 || isNaN(master))) ||
(visa.length > 0 && (visa.length !== 16 || isNaN(visa))) ||
(american.length > 0 && (american.length !== 15 || isNaN(american)))) {
alert("Please check your card details again");
return false;
} else if (postcode.length < 4 || (!postcode.match(/^[0-9]*$/))) {
alert("Please enter a valid postcode");
return false;
} else if (suburb.length < 8 || address.length < 8) {
alert("Please check your address, to confirm details");
return false;
}

Creating a pattern for a number which must be prefixed by 3 letters eg (IKA111111)

function validatetest(e)
{
debugger;
e.preventDefault();
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var title = document.getElementById("title").value;
var healthNumber = document.getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var telephoneNumber = parseInt(document.getElementById("telephoneNumber").value);
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
var validText = /^[a-zA-Z]*$/;
var validLastText = /^[a-zA-Z-]*$/;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
//var n = healthNumber.startsWith("ZHA");
if(firstName!="" && lastName!= "" && title!="" && email !="")
{
if(email.match(validEmail))
{
if(!isNaN(telephoneNumber) && telephoneNumber >= 11111111111 && telephoneNumber <= 99999999999)
{
if(firstName.match(validText) && firstName.length >1)
{
if(lastName.match(validLastText) && lastName.length> 1)
{
if(healthNumber.match(validHealth))
{
alert("All information is Validated");
return true;
}
else
{
alert("error error");
return false;
}
}
else
{
document.getElementById("error4").innerHTML="letters and hypen only";
return false;
}
}
else
{
document.getElementById("error").innerHTML="letters only and more then one character";
return false;
}
}
else
{
document.getElementById("error2").innerHTML="Telephone number must be 11 num digits long";
}
}
else
{
document.getElementById("error3").innerHTML="email is not a valid format ";
return false;
}
}
else
{
alert("All fields must be entered except telephone Number ");
return false;
}
}
i am trying to create a validation process by using a pattern for a user inputted healthnumber so that it validates whether 3 letters are entered followed by 6 numbers via user input. (MIC123456 is example so MIC always has to been entered , those specific letters)
Not sure if my technique is correct by using a pattern stored in the ValidHeath variable as you can i have used this idea for my email validation etc .
You have an extra + in your regex, make it
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
Demo
var isMatch = !!"IKA111111".match(/^[A-Z]{3}[0-9]{6}$/);
isMatch ? console.log( "Matching" ) : console.log( "Not Matching" );

Session storage option

I am new to learning session storage. At the moment session storage works except for state for my session storage does not work. The state doesn't get displayed once I go to another page or refresh the page, it will go blank like when you are filling in the form for the first time again. Html for state is as shown below. How do I properly code this for a session storage? I also do not want to have any JavaScript library in my code so a solution without it is mch appreciated.
<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>
JavaScript:
"use strict";
/*get variables from form and check rules*/
function validate(){
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
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
//Validation for Date of birth
if (age >= 80){ // Checks if age is over 80
errMsg = errMsg + "You must be 80 or younger to apply for this job\n";
result = false;
}
if (age <= 15){ // Checks if age is under 15
errMsg = errMsg + "You must be 15 or older to apply for this job\n";
result = false;
}
//Validation for state and corresponding postcode
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;
}
//Validation of other skill so checks if other skill box is checked and if so will check textbox for text
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
document.getElementById("error").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
//used 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;
}
}

JavaScript credit card validation

I am currently working on some homework for school and I am little stuck with my switch!
I am getting a response up until alert(card) in checkcard();
my problem is, none of the cases will actually validate the type of card that is is in reference too, I am not allowed to use any addons like jQuery etc etc.
I'll post relevant code and be glad to hear from you guys :D I've commented the lines with #### for ease. Also, getcard does return correct card type as wished.
function getCard(){
var cardType = "unknown";
var cardTypeArray = document.getElementById("chooseCard").getElementsByTagName("input");
for(var i = 0; i < cardTypeArray.length; i++){
if (cardTypeArray[i].checked) {
cardType = cardTypeArray[i].value;
}
}
alert ("cardtype is" + cardType);
return cardType;
}
function checkCard(cardNumber){
var errMsg = "";
var card = getCard();
//var cardNumber = document.getElementById("cardNumber").value;
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMaster = /^5[1-5][0-9]{14}$/;
var regAmerica = /^3[47][0-9]{13}$/;
alert(card); // works till here #######
switch(card){
case "Visa":
if (parseInt(cardNumber.substring(0,1)!=4) {
errMsg = "card number is not visa \n";
}
break;
case "Mastercard":
if (cardNumber.substring(0,1) !=5) {
errMsg = "card number is not mastercard. \n";
}
break;
case "AmericanExpress":
if (cardNumber.substring(0,2) !=51) {
errMsg = "card number not american express, \n";
}
break;
}
return errMsg;
}
function validator(){
var errMsg = ""; /* stores the error message */
var result = true;
var visaCard = document.getElementById("visa").checked;
var masterCard = document.getElementById("mastercard").checked;
var americanExpress = document.getElementById("americanExpress").checked;
var cardName = document.getElementById("cardName").value;
//document.getElementById("cardName").setAttribute('maxlength',40);
var regexAlpha = /^[a-zA-Z ]+$/;
var cardNumber = document.getElementById("cardNumber").value;
var regexNum = /^[0-9]+$/;
var date = new Date();
var todayDateMonth = date.getMonth() + 1;
var todayDateYear = date.getFullYear();
var expMonth = document.getElementById("expMonth").value;
var expYear = document.getElementById("expYear").value;
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMaster = /^5[1-5][0-9]{14}$/;
var regAmerica = /^3[47][0-9]{13}$/;
if (todayDateMonth > expMonth || todayDateYear > expYear){
errMsg += "expiry date is wrong\n";
result = false;
}
if (!(visaCard || masterCard || americanExpress)){
errMsg += "please select visa, mastercard or american express\n";
result = false;
} /* assumes no errors */
if (cardNumber.length > 16 || cardNumber.length < 15 )
{
errMsg = errMsg + "your card number can only contain 15 to 16 digits \n";
result = false;
}else{
checkCard(cardNumber); // Starts here #######
}
if (cardName.length > 40 || cardName.length < 1 || !regexAlpha.test(cardName))
{
errMsg = errMsg + "your card name must only contain alpha characters \n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result; //if false the information will not be sent to the server
}
function init() {
if(document.getElementById("regform")!==null){
var regForm = document.getElementById("regform");// get ref to the HTML element
regForm.onsubmit = validate;
prefill_form();
}
if(document.getElementById("bookform") !=null){
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validator; /* assigns functions to corresponding events */
var cancel = document.getElementById("cancelButton");
cancel.onclick = cancelBooking;
getBooking();
}
}
okay so the problem was that i was not returning an error message or a false result. ill re post the same code as before but what i added to make it work for those interested. thank you for the feed back! i will be taking a few points on board. anyway code is below, look for ###################.
function validator(){
var errMsg = "";
var result = true;
var visaCard = document.getElementById("visa").checked;
var masterCard = document.getElementById("mastercard").checked;
var americanExpress = document.getElementById("americanExpress").checked;
var cardName = document.getElementById("cardName").value;
var regexAlpha = /^[a-zA-Z ]+$/;
var cardNumber = document.getElementById("cardNumber").value;
var regexNum = /^[0-9]+$/;
var date = new Date();
var todayDateMonth = date.getMonth() + 1;
var todayDateYear = date.getFullYear();
var expDate = document.getElementById("expDate").value;
var dateFormat = /^[\d]{2}\/[\d]{4}$/;
if (!dateFormat.test(expDate)){
errMsg += "please select a valid date range\n";
result = false;
}else if (todayDateYear > expDate.substring(3,7)){
errMsg += "please select a valid expiry year\n";
result = false;
} else if (todayDateYear == expDate.substring(3,7) && todayDateMonth > expDate.substring(0,2)){
errMsg += "please select a valid expiry month\n";
result = false;
}
if (!(visaCard || masterCard || americanExpress)){
errMsg += "please select visa, mastercard or american express\n";
result = false;
}
if (cardNumber.length > 16 || cardNumber.length < 15 )
{
errMsg = errMsg + "your card number can only contain 15 to 16 digits \n";
result = false;
}else{
// code below is what i added ######################################
var tempMsg = checkCard(cardNumber);
if (tempMsg != "") {
errMsg = errMsg + tempMsg;
result = false;
};
}
if (cardName.length > 40 || cardName.length < 1 || !regexAlpha.test(cardName))
{
errMsg = errMsg + "your card name must only contain alpha characters \n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result; //if false the information will not be sent to the server
}
function checkCard(cardNumber){
var errMsg = "";
var card = getCard();
var cvv = document.getElementById("CVV").value;
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMaster = /^5[1-5][0-9]{14}$/;
var regAmerica = /^3[47][0-9]{13}$/;
var cvvCheck3 =/^[0-9]{3}$/;
var cvvCheck4 =/^[0-9]{4}$/;
//do with if else
switch(card){
case "Visa":
if (!regVisa.test(cardNumber) || !cvvCheck3.test(cvv)) {
errMsg = "card number is not visa or cvv is wrrong \n";
}
break;
case "Mastercard":
if (!regMaster.test(cardNumber) || !cvvCheck3.test(cvv)) {
errMsg = "card number is not mastercard or cvv is wrong\n";
}
break;
case "AmericanExpress":
if (!regAmerica.test(cardNumber) || !cvvCheck4.test(cvv)) {
errMsg = "card number not american express or cvv is wrong, \n";
}
break;
default:
errMsg = "we cant process this card number \n";
}
return errMsg;
}
The problem is with your code structure I see. You have an if condition inside of switch without any associated else. And without much knowledge of your test conditions I have good reason to believe you are not handling the cases and conditions properly. Simple way to find where your code went wrong is to put debugger; statement in your code. Have your developer tools open, you can do this by pressing F12 in most browsers or just from right click options. It should pause the execution of code there. Then there are two buttons you will see. 1. Play button which will resume code execution at once. 2. Kind of bent arrow, this is important one you can execute code line by line with this one and see which conditions were passed and which part of the code actually executed. Wanted to put this in comment but was too long to fit. If you have problems debugging feel free to comment here.And you can just google developer tools in case you can not open the particular window.

Validating using JavaScript - how to show to all validation error message's

I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
How do I get it so all validation messages show if the user has left all fields blank?
Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.
Try something like this (or add all your code if you need more details)
JavaScript:
function validateForm() {
var sName = document.forms["myForm"]["surname_5"].value;
var ret = true;
if (sName == null || sName == "") {
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
ret = false;
}
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "*First name is required";
ret = false;
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
ret = false;
}
return ret;
}

Categories

Resources