Javascript field validation inside forEach loop - javascript

I am building a complex registration form with javascript validation.
There are text fields inserted dynamically if the user states that they have children, the number of fields depends on how many children they say they have.
I get the nodes using const kidDobFields = agesRow.querySelectorAll('input[name^="age"]');
In my loop, I am first trying to ensure that the field is no empty, and then secondly ensure the date entered is not more than 16 years ago, if all fields are populated and valid then the form can go on to the next tab of questions.
if(document.getElementById('hasChildren').checked && numberKids.value != '') {
kidDobFields.forEach(field => {
if(field.value == '') {
error.style.display = "block";
error.innerHTML = 'Please enter all dates of birth.';
field.classList.add("is-invalid");
return;
} else {
var today = new Date();
var todayYear = today.getFullYear();
var todayMonth = today.getMonth()+1;
var todayDate = today.getDate();
var dobParts = field.value.split("/");
var dtDOB = new Date(dobParts[1] + "/" + dobParts[0] + "/" + dobParts[2]);
var dobYear = dtDOB.getFullYear();
var dobMonth = dtDOB.getMonth()+1;
var dobDate = dtDOB.getDate();
var age = 'valid';
if(todayYear - dobYear > 16) {
var age = 'invalid';
}
if(todayYear - dobYear == 16) {
if(todayMonth > dobMonth) {
var age = 'invalid';
}
if(todayMonth == dobMonth) {
if(todayDate > dobDate) {
var age = 'invalid';
}
}
}
if(age == 'invalid') {
error.style.display = "block";
error.innerHTML = 'Please don\'t include children who are aged 16 or over.';
field.classList.add("is-invalid");
return;
}
}
});
} else {
document.getElementById('tab3').style.display = "none";
document.getElementById('tab4').style.display = "block";
document.getElementById('formHeading').innerHTML = 'Availability';
document.getElementById('step3').classList.add("complete");
}
Using the code above, if I use 3 date fields and leave the first empty, the 2nd and 3rd are still validated.
If I put a date over 16 years ago in the first and leave the others empty, the error shows Please enter all dates of birth. because the loop continues, rather than stopping after the first and saying that the date is too old.
I know a forEach cannot be broken out of, but I am not sure how best to improve this validation process.

you need to use every() instead of forEach() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every?retiredLocale=uk
I found answer here: https://masteringjs.io/tutorials/fundamentals/foreach-break
your code will look like this:
if(document.getElementById('hasChildren').checked && numberKids.value != '') {
kidDobFields.every(field => {
if(field.value == '') {
error.style.display = "block";
error.innerHTML = 'Please enter all dates of birth.';
field.classList.add("is-invalid");
return false;
} else {
var today = new Date();
var todayYear = today.getFullYear();
var todayMonth = today.getMonth()+1;
var todayDate = today.getDate();
var dobParts = field.value.split("/");
var dtDOB = new Date(dobParts[1] + "/" + dobParts[0] + "/" + dobParts[2]);
var dobYear = dtDOB.getFullYear();
var dobMonth = dtDOB.getMonth()+1;
var dobDate = dtDOB.getDate();
var age = 'valid';
if(todayYear - dobYear > 16) {
var age = 'invalid';
}
if(todayYear - dobYear == 16) {
if(todayMonth > dobMonth) {
var age = 'invalid';
}
if(todayMonth == dobMonth) {
if(todayDate > dobDate) {
var age = 'invalid';
}
}
}
if(age == 'invalid') {
error.style.display = "block";
error.innerHTML = 'Please don\'t include children who are aged 16 or over.';
field.classList.add("is-invalid");
return false;
}
}
return true;
});
} else {
document.getElementById('tab3').style.display = "none";
document.getElementById('tab4').style.display = "block";
document.getElementById('formHeading').innerHTML = 'Availability';
document.getElementById('step3').classList.add("complete");
}

Related

Google Scripts - Using a drop-down menu to show a balance

So I have used data validation to create a drop-down menu that will then update some cells to show the budget amount that is remaining from another sheet. Nothing is occurring when I try to update the field.
The first check for if a checkbox is marked true all works, so I know it is entering the first if. I just can't seem to get it to enter the second if.
function onEdit(e) {
var sheet=e.range.getSheet();
var rgA1=e.range.getA1Notation();
if (sheet.getName()=="Entry") {
console.log("Entry")
if (e.value == "TRUE") {
submit();
Today();
e.range.setValue("FALSE");
}
if (rgA1=="A8" || rgA1 == "B8") {
var entry = e.source.getSheetByName("Entry");
var summary = e.source.getSheetByName("Summary");
var day = entry.getRange("B9").getValue();
var month = entry.getRange("B10").getValue();
var total = entry.getRange("B11").getValue();
var today = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yy");
//var daysRemaining = DATEIF(today, summary.getRange("D4"), "D");cell functions not allow
//var monthsRemaining = DATEIF(today, summary.getRange("D4"), "M");cell functions not allowed
console.log("Entered 2nd if")
if (e.value == summary.getRange("B59").getValue) {
var balance = summary.getRange("E59").getValue
console.log("Entered 3rd if")
}
else if (e.value == summary.getRange("B60").getValue()) {
var balance = summary.getRange("E60").getValue()
}
else if (e.value == summary.getRange("B61").getValue()) {
var balance = summary.getRange("E61").getValue()
}
else if (e.value == summary.getRange("B62").getValue()) {
var balance = summary.getRange("E62").getValue()
}
else if (e.value == summary.getRange("B63").getValue()) {
var balance = summary.getRange("E63").getValue()
}
else if (e.value == summary.getRange("B64").getValue()) {
var balance = summary.getRange("E64").getValue()
}
else if (e.value == summary.getRange("B65").getValue()) {
var balance = summary.getRange("E65").getValue()
}
else if (e.value == summary.getRange("B66").getValue()) {
var balance = summary.getRange("E66").getValue()
}
else if (e.value == summary.getRange("B67").getValue()) {
var balance = summary.getRange("E67").getValue()
}
else if (e.value == summary.getRange("B68").getValue()) {
var balance = summary.getRange("E68").getValue()
}
else if (e.value == summary.getRange("B69").getValue()) {
var balance = summary.getRange("E69").getValue()
}
else if (e.value == summary.getRange("B70").getValue()) {
var balance = summary.getRange("E70").getValue()
}
else if (e.value == summary.getRange("B71").getValue()) {
var balance = summary.getRange("E71").getValue()
}
day.setValue(balance / 56);
month.setValue(balance / 2);
total.setValue(balance);
}
}
}
Any thanks would be hugely appreciated!
EDIT 5/8/20
Fixed using Cooper's suggestions
Also here is a copy of the sheet this script is for.
That's better but you still have some problems at the end.
function onEdit(e) {
var sheet=e.range.getSheet();
var rgA1=e.range.getA1Notation();
if (sheet.getName()=="Entry") {
console.log("Entry")
if (e.value == "TRUE") {
submit();
Today();
e.range.setValue("FALSE");
}
if (rgA1=="A8" || rgA1 == "B8") {
var entry = e.source.getSheetByName("Entry");
var summary = e.source.getSheetByName("Summary");
var dA=entry.getRange('B9:B11').getValues();
var day = dA[0][0];
var month = dA[0][1];
var total = dA[0][2];
var today = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yy");
var bvs=summary.getRange('B59:B71').getValues();
var erg=summary.getRange('E59:E71');
var evs=erg.getValues();
for(var i=0;i<bvs.length;i++) {
if(e.value==bvs[i][0]) {
var balance=evs[i][0];
break;
}
}
entry.getRange('B9').setValue(balance/56);
entry.getRange('B10').setValue(balance/2);
entry.getRange('B11').setValue(balance);
//day.setValue(balance / 56);//day is not a range so there is no setValue Method
//month.setValue(balance / 2);//day is not a range so there is no setValue Method
//total.setValue(balance);//day is not a range so there is no setValue Method
}
}
}

input 0 is not defined stack:reference error

I am using scw date picker library. Javascript code that I used for a long time doesn't work now. onclick function of input works on the first row but doesn't work on second and other rows.
I created the inputs dynamically with javascript codes.
JavaScript Codes
function AddRow(tbody_id, satir_id)
{
var tbody = document.getElementById(tbody_id);
var row = document.createElement("tr");
row.id = "s" + satir_id;
var input0 = document.createElement("input");
input0.id = row.id + "_i0";
input0.name = "satir[" + satir_id+ "][0]";
input0.className = "text";
input0.size = "11";
input0.onclick = function onclick()
{
scwNextAction = tmp.runAfterSCW(this);
scwShow(this, event);
}
}
At this input0.onclick method work on first row. But it doesn't work on second and another rows.
Error is like below:
input0 is not defined
stack:"ReferenceError: input0 is not defined↵ at eval (eval at positiontip (http://portaltest.gural.tr/phpgroupware/kys/siparis/ortak/kutuphane/form.js?v2.0.1035:1:1), :1:1)↵ at HTMLDocument.positiontip (http://portaltest.gural.tr/phpgroupware/kys/siparis/ortak/kutuphane/form.js?v2.0.1035:334:21)"
The same code works at internet explorer but doesn't work at google crome. There is reference error at both of them(internet explorer,google chrome).
Do you think how can I fix this situation?
Can you try to addEventListener instead of using onclick property
function AddRow(tbody_id, satir_id)
{
var tbody = document.getElementById(tbody_id);
var row = document.createElement("tr");
row.id = "s" + satir_id;
var input0 = document.createElement("input");
input0.id = row.id + "_i0";
input0.name = "satir[" + satir_id+ "][0]";
input0.className = "text";
input0.size = "11";
input0.addEventlistener("click", function(evt) {
scwNextAction = tmp.runAfterSCW(this);
scwShow(this, evt);
})
}
Else, do you have reference to input0 in tmp.runAfterSCW() or scwShow() ?
I have scw.js for scw date picker library.
for runsAfterSCW function:
Function.prototype.runsAfterSCW =
function() {var func = this,
args = new Array(arguments.length);
for (var i=0;i<args.length;++i) {args[i] = arguments[i];}
return function()
{// concat/join the two argument arrays
for (var i=0;i<arguments.length;++i) {args[args.length] = arguments[i];}
return (args.shift()==scwTriggerEle)?func.apply(this, args):null;
};
};
For scwShow function:
function scwShow(scwEle,scwSource)
{if (!scwSource) {scwSource = window.event;}
if (scwSource.tagName) // Second parameter isn't an event it's an element
{var scwSourceEle = scwSource;
if (scwID('scwIE')) {window.event.cancelBubble = true;}
else {scwSourceEle.parentNode.addEventListener('click',scwStopPropagation,false);}
}
else // Second parameter is an event
{var scwSourceEle = (scwSource.target)
?scwSource.target
:scwSource.srcElement;
// Stop the click event that opens the calendar from bubbling up to
// the document-level event handler that hides it!
if (scwSource.stopPropagation) {scwSource.stopPropagation();}
else {scwSource.cancelBubble = true;}
}
scwTriggerEle = scwSourceEle;
// Take any parameters that there might be from the third onwards as
// day numbers to be disabled 0 = Sunday through to 6 = Saturday.
scwParmActiveToday = true;
for (var i=0;i<7;i++)
{scwPassEnabledDay[(i+7-scwWeekStart)%7] = true;
for (var j=2;j<arguments.length;j++)
{if (arguments[j]==i)
{scwPassEnabledDay[(i+7-scwWeekStart)%7] = false;
if (scwDateNow.getDay()==i) {scwParmActiveToday = false;}
}
}
}
// If no value is preset then the seed date is
// Today (when today is in range) OR
// The middle of the date range.
scwSeedDate = scwDateNow;
// Find the date and Strip space characters from start and
// end of date input.
var scwDateValue = '';
if (scwEle.value) {scwDateValue = scwEle.value.replace(/^\s+/,'').replace(/\s+$/,'');}
else {if (typeof scwEle.value == 'undefined')
{var scwChildNodes = scwEle.childNodes;
for (var i=0;i<scwChildNodes.length;i++)
{if (scwChildNodes[i].nodeType == 3)
{scwDateValue = scwChildNodes[i].nodeValue.replace(/^\s+/,'').replace(/\s+$/,'');
if (scwDateValue.length > 0)
{scwTriggerEle.scwTextNode = scwChildNodes[i];
scwTriggerEle.scwLength = scwChildNodes[i].nodeValue.length;
break;
}
}
}
}
}
// Set the language-dependent elements
scwSetDefaultLanguage();
scwID('scwDragText').innerHTML = scwDrag;
scwID('scwMonths').options.length = 0;
for (var i=0;i<scwArrMonthNames.length;i++)
{scwID('scwMonths').options[i] = new Option(scwArrMonthNames[i],scwArrMonthNames[i]);}
scwID('scwYears').options.length = 0;
for (var i=0;i<scwDropDownYears;i++)
{scwID('scwYears').options[i] = new Option((scwBaseYear+i),(scwBaseYear+i));}
for (var i=0;i<scwArrWeekInits.length;i++)
{scwID('scwWeekInit' + i).innerHTML = scwArrWeekInits[(i+scwWeekStart)%scwArrWeekInits.length];}
if (((new Date(scwBaseYear + scwDropDownYears, 0, 0)) > scwDateNow &&
(new Date(scwBaseYear, 0, 0)) < scwDateNow) ||
(scwClearButton && (scwEle.readOnly || scwEle.disabled))
) {scwID('scwFoot').style.display = '';
scwID('scwNow').innerHTML = scwToday + ' ' + scwDateNow.scwFormat(scwDateDisplayFormat);
scwID('scwClearButton').value = scwClear;
if ((new Date(scwBaseYear + scwDropDownYears, 0, 0)) > scwDateNow &&
(new Date(scwBaseYear, 0, 0)) < scwDateNow
) {scwID('scwNow').style.display = '';
if (scwClearButton && (scwEle.readOnly || scwEle.disabled))
{scwID('scwClear').style.display = '';
scwID('scwClear').style.textAlign = 'left';
scwID('scwNow').style.textAlign = 'right';
}
else {scwID('scwClear').style.display = 'none';
scwID('scwNow').style.textAlign = 'center';
}
}
else {scwID('scwClear').style.textAlign = 'center';
scwID('scwClear').style.display = '';
scwID('scwNow').style.display = 'none';
}
}
else {scwID('scwFoot').style.display = 'none';}
if (scwDateValue.length==0)
{// If no value is entered and today is within the range,
// use today's date, otherwise use the middle of the valid range.
scwBlnFullInputDate=false;
if ((new Date(scwBaseYear+scwDropDownYears,0,0))<scwSeedDate ||
(new Date(scwBaseYear,0,1)) >scwSeedDate
)
{scwSeedDate = new Date(scwBaseYear + Math.floor(scwDropDownYears / 2), 5, 1);}
}
else
{function scwInputFormat()
{var scwArrSeed = new Array(),
scwArrInput = scwDateValue.split(new RegExp('[\\'+scwArrDelimiters.join('\\')+']+','g'));
// "Escape" all the user defined date delimiters above -
// several delimiters will need it and it does no harm for
// the others.
// Strip any empty array elements (caused by delimiters)
// from the beginning or end of the array. They will
// still appear in the output string if in the output
// format.
if (scwArrInput[0]!=null)
{if (scwArrInput[0].length==0) {scwArrInput.splice(0,1);}
if (scwArrInput[scwArrInput.length-1].length==0) {scwArrInput.splice(scwArrInput.length-1,1);}
}
scwBlnFullInputDate = false;
scwDateOutputFormat = scwDateOutputFormat.toUpperCase();
// List all the allowed letters in the date format
var template = ['D','M','Y'];
// Prepare the sequence of date input elements
var result = new Array();
for (var i=0;i<template.length;i++)
{if (scwDateOutputFormat.search(template[i])>-1)
{result[scwDateOutputFormat.search(template[i])] = template[i];}
}
var scwDateSequence = result.join('');
// Separate the elements of the date input
switch (scwArrInput.length)
{case 1:
{if (scwDateOutputFormat.indexOf('Y')>-1 &&
scwArrInput[0].length>scwDateOutputFormat.lastIndexOf('Y'))
{scwArrSeed[0] = parseInt(scwArrInput[0].substring(scwDateOutputFormat.indexOf('Y'),
scwDateOutputFormat.lastIndexOf('Y')+1),10);
}
else {scwArrSeed[0] = 0;}
if (scwDateOutputFormat.indexOf('M')>-1 &&
scwArrInput[0].length>scwDateOutputFormat.lastIndexOf('M'))
{scwArrSeed[1] = scwArrInput[0].substring(scwDateOutputFormat.indexOf('M'),
scwDateOutputFormat.lastIndexOf('M')+1);
}
else {scwArrSeed[1] = '6';}
if (scwDateOutputFormat.indexOf('D')>-1 &&
scwArrInput[0].length>scwDateOutputFormat.lastIndexOf('D'))
{scwArrSeed[2] = parseInt(scwArrInput[0].substring(scwDateOutputFormat.indexOf('D'),
scwDateOutputFormat.lastIndexOf('D')+1),10);
}
else {scwArrSeed[2] = 1;}
if (scwArrInput[0].length==scwDateOutputFormat.length) {scwBlnFullInputDate = true;}
break;
}
case 2:
{// Year and Month entry
scwArrSeed[0] =
parseInt(scwArrInput[scwDateSequence.
replace(/D/i,'').
search(/Y/i)],10); // Year
scwArrSeed[1] = scwArrInput[scwDateSequence.
replace(/D/i,'').
search(/M/i)]; // Month
scwArrSeed[2] = 1; // Day
break;
}
case 3:
{// Day Month and Year entry
scwArrSeed[0] =
parseInt(scwArrInput[scwDateSequence.
search(/Y/i)],10); // Year
scwArrSeed[1] = scwArrInput[scwDateSequence.
search(/M/i)]; // Month
scwArrSeed[2] =
parseInt(scwArrInput[scwDateSequence.
search(/D/i)],10); // Day
scwBlnFullInputDate = true;
break;
}
default:
{// A stuff-up has led to more than three elements in
// the date.
scwArrSeed[0] = 0; // Year
scwArrSeed[1] = 0; // Month
scwArrSeed[2] = 0; // Day
}
}
// These regular expressions validate the input date format
// to the following rules;
// Day 1-31 (optional zero on single digits)
// Month 1-12 (optional zero on single digits)
// or case insensitive name
// Year One, Two or four digits
// Months names are as set in the language-dependent
// definitions and delimiters are set just below there
var scwExpValDay = new RegExp('^(0?[1-9]|[1-2][0-9]|3[0-1])$'),
scwExpValMonth = new RegExp('^(0?[1-9]|1[0-2]|' +
scwArrMonthNames.join('|') +
')$','i'),
scwExpValYear = new RegExp('^([0-9]{1,2}|[0-9]{4})$');
// Apply validation and report failures
if (scwExpValYear.exec(scwArrSeed[0]) == null ||
scwExpValMonth.exec(scwArrSeed[1]) == null ||
scwExpValDay.exec(scwArrSeed[2]) == null
)
{if (scwShowInvalidDateMsg)
{alert(scwInvalidDateMsg +
scwInvalidAlert[0] + scwDateValue +
scwInvalidAlert[1]);}
scwBlnFullInputDate = false;
scwArrSeed[0] = scwBaseYear +
Math.floor(scwDropDownYears/2); // Year
scwArrSeed[1] = '6'; // Month
scwArrSeed[2] = 1; // Day
}
// Return the Year in scwArrSeed[0]
// Month in scwArrSeed[1]
// Day in scwArrSeed[2]
return scwArrSeed;
};
// Parse the string into an array using the allowed delimiters
scwArrSeedDate = scwInputFormat();
// So now we have the Year, Month and Day in an array.
// If the year is one or two digits then the routine assumes a
// year belongs in the 21st Century unless it is less than 50
// in which case it assumes the 20th Century is intended.
if (scwArrSeedDate[0]<100) {scwArrSeedDate[0] += (scwArrSeedDate[0]>50)?1900:2000;}
// Check whether the month is in digits or an abbreviation
if (scwArrSeedDate[1].search(/\d+/)<0)
{for (i=0;i<scwArrMonthNames.length;i++)
{if (scwArrSeedDate[1].toUpperCase()==scwArrMonthNames[i].toUpperCase())
{scwArrSeedDate[1]=i+1;
break;
}
}
}
scwSeedDate = new Date(scwArrSeedDate[0],scwArrSeedDate[1]-1,scwArrSeedDate[2]);
}
// Test that we have arrived at a valid date
if (isNaN(scwSeedDate))
{if (scwShowInvalidDateMsg) {alert(scwInvalidDateMsg + scwInvalidAlert[0] + scwDateValue + scwInvalidAlert[1]);}
scwSeedDate = new Date(scwBaseYear + Math.floor(scwDropDownYears/2),5,1);
scwBlnFullInputDate=false;
}
else
{// Test that the date is within range,
// if not then set date to a sensible date in range.
if ((new Date(scwBaseYear,0,1)) > scwSeedDate)
{if (scwBlnStrict && scwShowOutOfRangeMsg) {alert(scwOutOfRangeMsg);}
scwSeedDate = new Date(scwBaseYear,0,1);
scwBlnFullInputDate=false;
}
else
{if ((new Date(scwBaseYear+scwDropDownYears,0,0))<scwSeedDate)
{if (scwBlnStrict && scwShowOutOfRangeMsg) {alert(scwOutOfRangeMsg);}
scwSeedDate = new Date(scwBaseYear + Math.floor(scwDropDownYears)-1,11,1);
scwBlnFullInputDate=false;
}
else
{if (scwBlnStrict && scwBlnFullInputDate &&
(scwSeedDate.getDate() != scwArrSeedDate[2] ||
(scwSeedDate.getMonth()+1) != scwArrSeedDate[1] ||
scwSeedDate.getFullYear() != scwArrSeedDate[0]
)
)
{if (scwShowDoesNotExistMsg) alert(scwDoesNotExistMsg);
scwSeedDate = new Date(scwSeedDate.getFullYear(),scwSeedDate.getMonth()-1,1);
scwBlnFullInputDate=false;
}
}
}
}
// Test the disabled dates for validity
// Give error message if not valid.
for (var i=0;i<scwDisabledDates.length;i++)
{if (!((typeof scwDisabledDates[i] == 'object') && (scwDisabledDates[i].constructor == Date)))
{if ((typeof scwDisabledDates[i] == 'object') && (scwDisabledDates[i].constructor == Array))
{var scwPass = true;
if (scwDisabledDates[i].length !=2)
{if (scwShowRangeDisablingError)
{alert(scwRangeDisablingError[0] + scwDisabledDates[i] + scwRangeDisablingError[1]);}
scwPass = false;
}
else
{for (var j=0;j<scwDisabledDates[i].length;j++)
{if (!((typeof scwDisabledDates[i][j] == 'object') && (scwDisabledDates[i][j].constructor == Date)))
{if (scwShowRangeDisablingError)
{alert( scwDateDisablingError[0] + scwDisabledDates[i][j] + scwDateDisablingError[1]);}
scwPass = false;
}
}
}
if (scwPass && (scwDisabledDates[i][0] > scwDisabledDates[i][1])) {scwDisabledDates[i].reverse();}
}
else
{if (scwShowRangeDisablingError) {alert(scwDateDisablingError[0] + scwDisabledDates[i] + scwDateDisablingError[1]);}}
}
}
// Calculate the number of months that the entered (or
// defaulted) month is after the start of the allowed
// date range.
scwMonthSum = 12*(scwSeedDate.getFullYear()-scwBaseYear)+scwSeedDate.getMonth();
scwID('scwYears' ).options.selectedIndex = Math.floor(scwMonthSum/12);
scwID('scwMonths').options.selectedIndex = (scwMonthSum%12);
// Check whether or not dragging is allowed and display drag handle if necessary
scwID('scwDrag').style.display=(scwAllowDrag)?'':'none';
// Display the month
scwShowMonth(0);
// Position the calendar box
// The object sniffing for Opera allows for the fact that Opera
// is the only major browser that correctly reports the position
// of an element in a scrollable DIV. This is because IE and
// Firefox omit the DIV from the offsetParent tree.
scwTargetEle=scwEle;
var offsetTop =parseInt(scwEle.offsetTop ,10) + parseInt(scwEle.offsetHeight,10),
offsetLeft=parseInt(scwEle.offsetLeft,10);
if (!window.opera)
{while (scwEle.tagName!='BODY' && scwEle.tagName!='HTML')
{offsetTop -=parseInt(scwEle.scrollTop, 10);
offsetLeft-=parseInt(scwEle.scrollLeft,10);
scwEle=scwEle.parentNode;
}
scwEle=scwTargetEle;
}
do {scwEle=scwEle.offsetParent;
offsetTop +=parseInt(scwEle.offsetTop, 10);
offsetLeft+=parseInt(scwEle.offsetLeft,10);
}
while (scwEle.tagName!='BODY' && scwEle.tagName!='HTML');
if (scwAutoPosition)
{var scwWidth = parseInt(scwID('scw').offsetWidth, 10),
scwHeight = parseInt(scwID('scw').offsetHeight,10),
scwWindowLeft =
(document.body && document.body.scrollLeft)
?document.body.scrollLeft //DOM compliant
:(document.documentElement && document.documentElement.scrollLeft)
?document.documentElement.scrollLeft //IE6+ standards compliant
:0, //Failed
scwWindowWidth =
(typeof(innerWidth) == 'number')
?innerWidth //DOM compliant
:(document.documentElement && document.documentElement.clientWidth)
?document.documentElement.clientWidth //IE6+ standards compliant
:(document.body && document.body.clientWidth)
?document.body.clientWidth //IE non-compliant
:0, //Failed
scwWindowTop =
(document.body && document.body.scrollTop)
?document.body.scrollTop //DOM compliant
:(document.documentElement && document.documentElement.scrollTop)
?document.documentElement.scrollTop //IE6+ standards compliant
:0, //Failed
scwWindowHeight =
(typeof(innerHeight) == 'number')
?innerHeight //DOM compliant
:(document.documentElement && document.documentElement.clientHeight)
?document.documentElement.clientHeight //IE6+ standards compliant
:(document.body && document.body.clientHeight)
?document.body.clientHeight //IE non-compliant
:0; //Failed
offsetLeft -= (offsetLeft - scwWidth + parseInt(scwTargetEle.offsetWidth,10) >= scwWindowLeft &&
offsetLeft + scwWidth > scwWindowLeft + scwWindowWidth
)?(scwWidth - parseInt(scwTargetEle.offsetWidth,10)):0;
offsetTop -= (offsetTop - scwHeight - parseInt(scwTargetEle.offsetHeight,10) >= scwWindowTop &&
offsetTop + scwHeight > scwWindowTop + scwWindowHeight
)?(scwHeight + parseInt(scwTargetEle.offsetHeight,10)):0;
}
scwID('scw').style.top = offsetTop+'px';
scwID('scw').style.left = offsetLeft+'px';
scwID('scwIframe').style.top = offsetTop+'px';
scwID('scwIframe').style.left = offsetLeft+'px';
scwID('scwIframe').style.width =(scwID('scw').offsetWidth-(scwID('scwIE')?2:4))+'px';
scwID('scwIframe').style.height=(scwID('scw').offsetHeight-(scwID('scwIE')?2:4))+'px';
scwID('scwIframe').style.visibility='inherit';
// Show it on the page
scwID('scw').style.visibility='inherit';
};

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" );

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.

JavaScript code i have applied on a calendar plugin is working till November , but not on december

This is the code.
.controller('CalendarCtrl',function($scope,$state,ProjectServices,$filter){
var _date = $filter('date')(new Date(), 'yyyy-MM-dd');
$scope.data = { embeddedDate: _date };
$scope.userData=$state.params.username;
$scope.employeeName = $state.params.employeeName;
$scope.mgrApprvemployeeId = $state.params.employeeID;
$scope.projectName = $state.params.projectName;
if(localStorage.getItem('employeeInfo')){
var employeeDetails = JSON.parse(localStorage.getItem('employeeInfo'));
if ($scope.mgrApprvemployeeId) {
$scope.calprofile= true;
employeeId = $scope.mgrApprvemployeeId;
$scope.mgrRsrcDetails = true;
}
else {
$scope.calprofile= false;
employeeId = employeeDetails.employeeId;
$scope.mgrRsrcDetails = false;
};
};
//localStorage.setItem('userselecteddate',JSON.stringify(data));
$scope.onTimeSet=function(newDate,oldDate){
var date= new Date(newDate),
day = (date.getDate() < 10 ? '0' : '') + date.getDate();
//day=date.getDate(),
//month=date.getMonth()+1,
month = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
year=date.getFullYear();
// week = date.getWeeks();
if(date.getDay() == 6 || date.getDay() == 0)
//if (true)
{
alert('You are submitting for a weekend!');
};
selectedDateUser=year+"-"+month+"-"+day;
$scope.data = { embeddedDate: selectedDateUser};
if (!$scope.mgrApprvemployeeId) {
$state.go('app.dayview',{calendarDate:selectedDateUser,username:$scope.userData});
} else {
$state.go('app.manager-dayview',{calendarDate:selectedDateUser,userEmployeeId:$scope.mgrApprvemployeeId,userEmployeeName:$scope.employeeName,userProjectName:$scope.projectName});
};
}
$scope.beforeRender = function ($view, $dates, $leftDate, $upDate, $rightDate) {
var todaysDate = new Date();
var currentMonth = todaysDate.getMonth()+1;
var currentYear = todaysDate.getFullYear();
var currentDay = todaysDate.getDate();
var rightDate = $rightDate.utcDateValue;
var rightFormDate = new Date(rightDate);
var selectedMonth = rightFormDate.getMonth();
var selectedYear = rightFormDate.getFullYear();
if (currentMonth == selectedMonth && currentYear == selectedYear) {
$rightDate.selectable = false;
};
angular.element(document).ready(function () {
ProjectServices.getEmployeeEffortHrs(employeeId).then(function(data) {
angular.forEach(data, function(data) {
//console.log(data.effort_date);
var effort_date = new Date(data.effort_date);
var date = effort_date.getDate();
var monthService = effort_date.getMonth()+1;
var approvedStatus = data.approveStatus;
// datesArray.push(date);
//console.log(date);
var totalEffortHours = data.total_effort;
jQuery('div.datetimepicker table.day-view tbody tr td').each(function(index){
// console.log(index);
//console.log('1234');
var str = $(this).text();
if((str.substr(0,str.indexOf(' ')) == date) && selectedMonth == monthService){
//$(this).removeClass("pending-hrs").addClass("filled-hrs");
// $(this).removeClass('pending-hrs');
// $(this).addClass('filled-hrs');
if(totalEffortHours <= 8){
$(this).removeClass('pending-hrs');
$(this).addClass('filled-hrs');
if (!$scope.mgrApprvemployeeId) {
$dates[index].selectable = false;
};
}else {
$(this).removeClass('pending-hrs');
$(this).addClass('holiday-leave');
if (!$scope.mgrApprvemployeeId) {
$dates[index].selectable = false;
};
};
// e.stopPropagation();
// $(this).html(date + <br/> + totalEffortHours);
if(approvedStatus == "Reject"){
var stringDisplay = date+"<span class='rejected-timesheet'>"+"Rejected"+" </span> ";
//$(this).removeClass('disabled');
$dates[index].selectable = true;
} else{
var stringDisplay = date+"<span>"+totalEffortHours +" hrs</span>";
//$(this).addClass('disabled');
$(this).selectable = true;
};
var escaped = $(this).text(stringDisplay).text();
$(this).html(escaped.replace(/\n/g, '<br />'));
//$(this).html($(this).html().replace(/\n/g,'<br/>'));
}
});
/*if (calendarDateDay == date) {
alert(111);
$dates[j].display = $dates[j].display + " <br/>" + totalEffortHours;
}; */
});
});
for (var j=0; j < 37; j++) {
var calendarUtcDates = $dates[j].utcDateValue;
var calendarDates = new Date(calendarUtcDates);
var calendarDateDay = calendarDates.getDate();
var calendarDateMonth = calendarDates.getMonth()+1;
var calendarDateYear = calendarDates.getFullYear();
if (calendarDateMonth == selectedMonth)
{
jQuery('div.datetimepicker table.day-view tbody tr td').each(function(){
if(($(this).text() == $dates[j].display) && calendarDateMonth == selectedMonth){
$(this).addClass('pending-hrs');
}
if (currentMonth == calendarDateMonth && currentYear == calendarDateYear && currentDay <= calendarDateDay ) {
$dates[j].future = true;
}
});
if (currentMonth == calendarDateMonth && currentYear == calendarDateYear && currentDay > calendarDateDay ) {
$dates[j].display = $dates[j].display + "<span> Pending</span>";
}else if(currentMonth > calendarDateMonth && currentYear == calendarDateYear){
$dates[j].display = $dates[j].display + "<span> Pending</span>";
};
};
if (currentMonth == calendarDateMonth && currentYear == calendarDateYear && currentDay == calendarDateDay )
{
//console.log('today date');
$dates[j].display = $dates[j].display + "<span>Today</span>";
};
}
});
}
}).filter("sanitize", ['$sce', function($sce) {
return function(htmlCode) {
return $sce.trustAsHtml(htmlCode);
}
}])
The above code gives the output as if the user fill the effort it has show in green. it is achieved by adding a class. If the user's effort is rejected by the manager, it is should display in another color. It is achieved by adding a span. if the user's effort is pending it should be displayed in another color. It is also done by adding a class. But these are working only till november. only for december it is not working. can anybody help me please.

Categories

Resources