The error I am seeing that Johnny999 keeps getting stored when the user inputs and loops back to type in that does not contain a number.
async function main() {
let userChoice;
let clientArray = [];
do {
output("1. Create a new profile:\n2. View previous profile:\n3. Quit application:");
let userChoice = await input("Please select an option:");
switch (Number(userChoice)) {
case 1:
//FirstName
let theirName = false;
while (!theirName) {
let firstName = await input("Please enter your first name: ");
theirName = checkName(firstName);
clientArray.push(firstName);
if (!theirName) {
output("Your first name contained numeric. Please re-enter your name without a numeric! ");
} else {
output("Your first name is: " + firstName);
}
}
//LastName
let theirName2 = false;
while (!theirName2) {
let lastName = await input("Please enter your last name: ");
theirName2 = checkName(lastName);
clientArray.push(lastName);
if (!theirName2) {
output("Your last name contained numeric. Please re-enter your name without a numeric! ");
} else {
output("Your last name is: " + lastName);
}
}
//Address
let theirAddress = false;
while (!theirAddress) {
let address = await input("Please enter your address: ");
theirAddress = validateMail(address);
clientArray.push(address);
if (!theirAddress) {
output("Not a valid address: ");
} else {
output("Your address is: " + address);
}
}
//DateOfPurchase
let dateOfPurchase = false;
while (!dateOfPurchase) {
let purchaseDate = await input("Please enter your purchase date YYYY-MM-DD: ");
dateOfPurchase = checkDate(purchaseDate);
clientArray.push(purchaseDate);
if (!dateOfPurchase) {
output("That is not a valid date:");
} else {
output("Your purchase date is: " + purchaseDate);
}
}
//Brand
let theirBrand = false;
while (!theirBrand) {
let brand = await input("Please enter brand of the vehicle: ");
theirBrand = checkBrand(brand);
clientArray.push(brand);
if (!theirBrand) {
output("Is not a valid brand! Please selecta valid brand: ");
} else {
output("Your preferred brand is: " + brand);
}
}
//Model
let vehicleModel = false;
while (!vehicleModel) {
let models = await input("Please choose your model you've selected: ");
vehicleModel = checkMake(models);
clientArray.push(models);
if (!vehicleModel) {
output("Not a brand, please select the right brand: ");
} else {
output("Your preferred brand is: " + models);
}
}
// Client Year
let theirYear = false;
while (!theirYear) {
let clientYear = await input("Please enter car year: YYYY-MM-DD: ");
theirYear = checkDate(clientYear);
clientArray.push(clientYear);
if (!theirYear) {
output("Not a date! No month above 12 or days above 31: ");
} else {
output("Your purchased date input: " + clientYear);
}
}
//VehicleVin
let vehicleVin = false;
while (!vehicleVin) {
let vins = await input("Please enter your VIN: ");
vehicleVin = carVin(vins);
clientArray.push(vins);
if (!vehicleVin) {
output("Must be a valid VIN using only numerical or alphabetic: ");
} else {
output("Your vehicle VIN is: " + vins);
}
}
break;
case 2:
let clientString = "";
for (let i = 0; i < clientArray.length; i++) {
clientString += clientArray[i] + " ,\n";
}
output(clientString)
break;
case 3:
output("Have a good day!");
break;
default:
output("That is not a valid menu choice.");
break;
}
}
while (userChoice != 3);
}
/*------------------------------------------------------------*/
function checkDate(inputValue)
// Take in a string from the user, return true if it is a date in the format YYYY-MM-DD where MM<=12 and DD<=31, and false if it isn't.
{
let outputValue = true;
let inputDate = inputValue.split("-");
// Validate Year
if (!checkYear(inputDate[0])) {
outputValue = false;
}
// Validate Month
if (inputDate[1] < 1 || inputDate[1] > 12 || !Number.isInteger(Number(inputDate[1]))) {
outputValue = false;
}
// Validate Day
if (inputDate[2] < 1 || inputDate[2] > 31 || !Number.isInteger(Number(inputDate[2]))) {
outputValue = false;
}
return outputValue;
}
function checkName(nameCheck) {
let nameValue = true;
const searchName = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
for (item of searchName) {
if (nameCheck.includes(item)) {
nameValue = false;
}
}
return nameValue;
}
function validateMail(mailAdress) {
let mailValue = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (mailAdress.match(mailValue)) {
return false;
} else {
return true;
}
}
function checkBrand(nameCheck) {
let nameValue = false;
const searchName = ["chevrolet", "ford", "gmc", "kia", "bmw", "volvo", "saab", "mitsubishi"];
for (item of searchName) {
if (nameCheck.toLowerCase().includes(item)) {
nameValue = true;
}
}
return nameValue;
}
function checkMake(theirMake) {
let makeValue = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (theirMake.match(makeValue)) {
return false;
} else {
return true;
}
}
function checkYear(inputValue) {
let outputValue = false;
return Number(inputValue) >= 1900 && Number(inputValue <= new Date().getFullYear());
}
function carVin(inputValue) {
let nameValue = true;
if (inputValue.length != 17) {
nameValue = false;
} else if (inputValue.match("^[A-Z0-9]*$") == null); {
}
return nameValue;
}
Welcome to SO!
It looks like your function is pushing the data to clientArray regardless of the output of the checkName() function, for example. Whatever value the user submits will be added because the output of checkName() is evaluated after the push. Here's one solution:
//FirstName
let theirName = false;
while (!theirName) {
let firstName = await input("Please enter your first name: ");
theirName = checkName(firstName);
if (!theirName) {
output("Your first name contained numeric. Please re-enter your name without a numeric! ");
} else {
clientArray.push(firstName);
output("Your first name is: " + firstName);
}
}
This only pushes the data to clientArray once we know that the name has only valid characters within it.
I also looked through your checkName() function. While your solution is functional, it might be more elegant to check against a regular expression (like in the other functions). I've included a solution for your scenario below.
function checkName(nameCheck) {
let nameValue = /[0-9]+/;
if (nameCheck.match(nameValue)) {
return false;
} else {
return true;
}
}
Related
I did my form validation first and it worked.However, after i include my other functions in my javascript file, it stops working. I try to check all the functions but i couldnt find where did i do wrong. Im still new to javascript so thank you in advance for those that took their time to fix my problem.
var gErrorMsg = "";
function validateForm() {
"use strict";
var isAllOK = false;
gErrorMsg = "";
var fnameOK = FName();
var lnameOK = LName();
var emailOK = Email();
var addOK = Address()
var cityOk = City();
var pnOK = PN();
if (fnameOK && lnameOK && emailOK && addOK && cityOk && pnOK) {
isAllOK = true;
}
else {
alert(gErrorMsg);
gErrorMsg = "";
isAllOK = false;
}
return isAllOK;
}
function FName() {
var owner = document.getElementById("name").value;
var pattern = /^[a-zA-Z ]+$/
var nameOk = true;
if ((owner.length == 0)) {
gErrorMsg = gErrorMsg + "Your first name cannot blank**\n"
nameOk = false;
}
else {
if (!pattern.test(owner)) {
gErrorMsg = gErrorMsg + "Your first name must only contain alpha characters**\n"
nameOk = false;
}
}
return nameOk;
}
function LName() {
var owner = document.getElementById("Lname").value;
var pattern = /^[a-zA-Z ]+$/
var nameOk = true;
if ((owner.length == 0)) {
gErrorMsg = gErrorMsg + "Your last name cannot blank**\n"
nameOk = false;
}
else {
if (!pattern.test(owner)) {
gErrorMsg = gErrorMsg + "Your last name must only contain alpha characters**\n"
nameOk = false;
}
}
return nameOk;
}
function Email() {
var email = document.getElementById("email");
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email.value)) {
result = true;
}
else { //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address **\n"
}
return result;
}
function Address() {
var add = document.getElementById("address").value;
var addOk = true;
if ((add.length == 0)) {
gErrorMsg = gErrorMsg + "Your address cannot blank**\n"
addOk = false;
}
return addOk;
}
function City() {
var city = document.getElementById("city").value;
var pattern = /^[a-zA-Z ]+$/
var cityOk = true;
if ((city.length == 0)) {
gErrorMsg = gErrorMsg + "Please state the city you are form**\n"
cityOk = false;
}
else {
if (!pattern.test(city)) {
gErrorMsg = gErrorMsg + "Your city name must only contain alpha characters**\n"
cityOk = false;
}
}
return cityOk;
}
function PN() {
var pn = document.getElementById("phone").value;
var pnOk = true;
var pattern = /^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g;
if ((pn.length == 0)) {
gErrorMsg = gErrorMsg + "Please state your contact number**\n"
pnOk = false;
}
else {
if (!pattern.test(pn)) {
gErrorMsg = gErrorMsg + "Your contact number should only has 10 numbers*\n"
pnOk = false;
}
}
return pnOk;
}
function storeitem(item_id) {
sessionStorage.setItem("item_id", item_id);
window.location.replace("enquiry.html");
}
function displayitem() {
document.getElementById("sbj").value = "RE: Enquiry on " + sessionStorage.getItem("item_id");
}
function validateForm() {
var product = document.getElementById("type").value;
sessionStorage.product = product;
return result;
}
//Store individual product page into sessionStorage
function storeProduct(productName) {
var options = ["Runway", "Commercial", "Fitness", "Fashion"];
options.forEach(array);
function array(value) {
if (value == productName) {
sessionStorage.productIndex = options.indexOf(value);
}
}
}
//Fill the subject field with the value of product
function storeSub() {
document.getElementById("type").selectedIndex = sessionStorage.productIndex;
var product = document.getElementById("type").value;
sessionStorage.subject = product;
document.getElementById("subject").value = sessionStorage.subject;
}
//Storing first optgroup into array
function productlist1() {
var select = document.getElementById("type");
var options = ["Runway", "Commercial", "Fitness", "Fashion"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
//change the value of the session storage according to the new product selected by user
function change() {
var product = document.getElementById("type").value;
sessionStorage.product = product;
document.getElementById("subject").value = sessionStorage.product;
}
//if validateForm returns returns false nothing will be sent to the server
function init() {
var regForm = document.getElementById("form");
//Lecture 7 - following 2 calls register inputs elements to respond to onblur and onclick events.
//registerInputsOnBlur();
//registerInputsOnClick();
regForm.onsubmit = validateForm;
displayitem()
}
window.onload = init;
(I would like to adress that English is not my first language)
I have this problem with javascript for a very long time and I don't know what to do.
This javascript is for a registration. Sometimes it gives access even though I haven't typed everything, or it doesn't give access even though I have typed everything correctly
If someone can help thanks already!
function validateform() {
var res = true;
res = userNameVal() && res;
res = passowrdVal() && res;
res = ConfirmPhone() && res;
res = emailConfirm() && res;
res = Name() && res;
res = lastName() && res;
res = city() && res;
return res;
}
function Name() {
var firstName = document.getElementById("firstName").value;
var msgBox = document.getElementById("NameMsg");
if (firstName.length == 0) {
msgBox.innerHTML = "You must enter your name";
return false;
}
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (reg.test(firstName) && reg1.test(firstName) && reg2.test(firstName) && (English(firstName))) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function lastName() {
var LastName = document.getElementById("LastName").value;
var msgBox = document.getElementById("LastNameMsg");
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (Name.length == 0) {
msgBox.innerHTML = "You must enter your name";
return false;
}
if (reg.test(LastName) || reg1.test(LastName) || reg2.test(LastName)) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function city() {
var CityName = document.getElementById("CityName").value;
var msgBox = document.getElementById("CityNameMsg");
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (CityName.length == 0) {
msgBox.innerHTML = "You must enter your City";
return false;
}
if (reg.test(CityName) || reg1.test(CityName) || reg2.test(CityName)) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function userNameVal() {
var userName = document.getElementById("userName").value;
var msgBox = document.getElementById("userNameMsg");
if (userName.length == 0) {
msgBox.innerHTML = "You must enter a username";
return false;
}
if (!isLetter(userName[0])) {
msgBox.innerHTML = "Your username must start with a letter";
return false;
}
msgBox.innerHTML = "";
return true;
}
function passowrdVal() {
var pass = document.getElementById("password").value;
var msgBox = document.getElementById("passwordMsg");
var specialChar = /[#!#$%^&*()-+]/;
if (pass.length == 0) {
msgBox = "You must enter a password";
return false;
}
if (pass.length < 7) {
msgBox.innerHTML = "The password must contain at least 7 charactes"
return false;
}
if (!specialChar.test(pass)) {
msgBox.innerHTML = "password must contain one special letter ";
return false;
}
msgBox.innerHTML = "";
return true;
}
function ConfirmPhone() {
var phone = document.getElementById("phone").value;
var msgBox = document.getElementById("phoneMsg");
var reg = /^0{1}(2|3|4|6|8|9|5[0|[2-8]|73)-?[1-9]\d{6}$/;
if (!reg.test(phone)) {
msgBox.innerHTML = "Phone number is illegal";
return false;
}
msgBox.innerHTML = "";
return true;
}
function emailConfirm() {
var email = document.getElementById("email").value;
var msgBox = document.getElementById("emailMsg");
var reg = /^\w+/;
if (!reg.text(email)) {
msgBox.innerHTML = "Mail can hava only one following letter";
return false;
}
msgBox.innerHTML = "";
reg = /^\w+([\.-]?\w+)*#\w+/;
if (!reg.test(email)) {
msgBox.innerHTML = "Mail must have #";
return false;
}
reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!reg.test(email)) {
msgBox.innerHTML = "invalid email";
return false;
}
msgBox.innerHTML = "";
return true;
}
function isLetter(ch) {
if ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z"))
return true;
return false;
}
function isDigit(ch) {
if (ch >= "0" && ch <= "9")
true;
false;
}
function English(str) {
i = 0;
while (str[i].isLetter) {
i++;
}
if (i == str.length())
return true;
return false;
}
We need more information about exactly what happens in your success and failure cases. However I see potential issues here:
For me, this function does not work for two reasons:
function English(str) {
i = 0;
while (str[i].isLetter) {
i++;
}
if (i == str.length())
return true;
return false;
}
First, the variable i is not declared, do you mean this:
let i = 0
Possibly, i is declared globally, and so you are inadvertently trashing another value? Generally using let is preferable to using var, you can have other unexpected effects on globals if you use var.
Second, I don't see how this is working. For me str[i].isLetter is not defined.
while (str[i].isLetter) {
Do you intend to use your isLetter() function
isLetter(str[i])
If that doesn't help you will need to explain in more detail what happens in your failure cases.
I created a function to encrypt and decrypt messages. the encrypting works fine. but when I try to log encrypted Hello World! it just logs H.
const chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".split("");
const numbs = "0123456789".split("");
const symbols = "!##$%^&*()_+-=[]{}|;':,./<>?\" ".split("");
function encrypt(message) {
message = message.split("")
var output = []
message.forEach(element => {
if (chars.includes(element)) {
output.push("c" + chars.indexOf(element))
} else if (numbs.includes(element)) {
output.push("n" + numbs.indexOf(element))
} else if (symbols.includes(element)) {
output.push("s" + symbols.indexOf(element))
} else {
console.log(element)
throw new Error(`Unknown character`)
}
});
return output.join("")
}
function decrypt(message) {
message = message.split("");
var output = [];
var prevDeter;
var prevNumbs = [];
message.forEach(element => {
if (element == "c") {
prevDeter = "c"
if (prevNumbs.length > 0) {
output.push(chars[parseInt(prevNumbs.join(""))])
}
} else if (element == "n") {
prevDeter = "n"
if (prevNumbs.length > 0) {
output.push(numbs[parseInt(prevNumbs.join(""))])
}
} else if (element == "s") {
prevDeter = "s"
if (prevNumbs.length > 0) {
output.push(symbols[parseInt(prevNumbs.join(""))])
}
} else {
prevNumbs.push(element)
}
});
return output.join("")
}
//expected to log Hello World! but logs H and when starting the message with a symbol or number it just logs nothing
console.log(decrypt(encrypt("Hello World!")))
Fixed it, i edited the encoding system to place a - between chars and the decoding system to just split the message at - and check if the element starts with c n or s. and then i just used substring to get the number and decrypt it
const chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".split("");
const numbs = "0123456789".split("");
const symbols = "!##$%^&*()_+-=[]{}|;':,./<>?\" ".split("");
function encrypt(message) {
message = message.split("");
var output = [];
message.forEach(element => {
if(chars.includes(element)) {
output.push("-c" + chars.indexOf(element));
}else if(numbs.includes(element)) {
output.push("-n" + numbs.indexOf(element));
}else if(symbols.includes(element)) {
output.push("-s" + symbols.indexOf(element));
}else{
console.log(element);
throw new Error(`Unknown character`);
};
});
return output.join("");
};
function decrypt(message) {
message = message.split("-");
console.log(message)
var output = [];
message.forEach(element => {
if(element.startsWith("c")) {
output.push(chars[element.substring(1)]);
}else if(element.startsWith("n")) {
output.push(numbs[element.substring(1)]);
}else if(element.startsWith("s")) {
output.push(symbols[element.substring(1)]);
}else if(element.length < 1){
}else{
throw new Error(`Invalid message`);
}
});
return output.join("");
};
console.log(decrypt(encrypt("Hello World!")));
You need to split the encoded string based on set/index pairs. This is easy enough to do with a look-ahead regular expression and splitting before a c, n or an s. /(?=[cns])/
const chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".split("");
const numbs = "0123456789".split("");
const symbols = "!##$%^&*()_+-=[]{}|;':,./<>?\" ".split("");
function encrypt(message) {
message = message.split("")
var output = []
message.forEach(element => {
if (chars.includes(element)) {
output.push("c" + chars.indexOf(element))
} else if (numbs.includes(element)) {
output.push("n" + numbs.indexOf(element))
} else if (symbols.includes(element)) {
output.push("s" + symbols.indexOf(element))
} else {
console.log(element)
throw new Error(`Unknown character`)
}
});
return output.join("")
}
function decrypt(message) {
message = message.split(/(?=[cns])/);
var output = [];
message.forEach(element => {
let set;
switch(element[0]){
case 'c':
set = chars;
break;
case 'n':
set = numbs;
break;
case 's':
set = symbols;
break;
}
const index = parseInt(element.substring(1));
output.push(set[index]);
});
return output.join('');
}
const encrypted = encrypt("Hello World!");
console.log(encrypted);
//expected to log Hello World! but logs H and when starting the message with a symbol or number it just logs nothing
console.log(decrypt(encrypted));
Heading
Hi, I have a lambda running javascript that uses an api to create and update records from one system and into another.
It works but takes a while because the dml statement is in a loop. I really need to iterate over the array and create one instance of the object to update, but am not very familiar with xml.
Based on documentation here is the format I need for multiple records:
<update>
<technician>
<id>1355196</id>
<name>Jim Smith</name>
<business_unit>Plumbing Service</business_unit>
</technician>
<technician>
<id>1355200</id>
<name>John Doe</name>
<business_unit>HVAC Sales</business_unit>
</technician>
</update>
Right now this is format I have, updating one at a time:
1st update call:
<update>
<technician>
<id>1355196</id>
<name>Jim Smith</name>
<business_unit>Plumbing Service</business_unit>
</technician>
</update>
2nd update call:
<update>
<technician>
<id>1355200</id>
<name>John Doe</name>
<business_unit>HVAC Sales</business_unit>
</technician>
</update>
And so on...
Here is the code I have now, one record at a time:
async function updateTechnicians(location, itechs, stechs) {
let logger = bootstrap.logger();
try {
const client = bootstrap.client(logger);
let sTechMap = new Map();
for(const tech in stechs){
sTechMap.set(parseInt(stechs[tech].id).toString(), stechs[tech])
}
for(const tech in itechs){
if(itechs[tech].location == location){
let thisTech = sTechMap.get(itechs[tech].servicetitanid)
let update = new UpdateTechnician();
if(thisTech){
update.id = itechs[tech].id;
update.name = thisTech.name;
update.database_active = thisTech.active;
if(thisTech.businessUnit != null){
update.tenant = thisTech.businessUnit.tenant.name;
update.business_unit = thisTech.businessUnit.name;
if(thisTech.businessUnit.name.includes('Phx')){ update.branch = 'Phoenix'; }
else if(thisTech.businessUnit.name.includes('Tuc')){ update.branch = 'Tucson'; }
else if(thisTech.businessUnit.name.includes('Simi')){ update.branch = 'Simi Valley'; }
else if(location == 'NV'){ update.branch = 'Las Vegas'; }
else if(location == 'CA'){ update.branch = 'Corona'; }
}
if(itechs[tech].deactivatedOn != ''){
update.deactivatedOn == '';
}
const response = await client.execute(update);
const result = response.getResult();
}
else{
let today = new Date();
let date = (today.getMonth()+1)+'/'+today.getDate()+'/'+today.getFullYear();
update.id = itechs[tech].id;
update.name = itechs[tech].name;
update.database_active = false;
if(itechs[tech].deactivatedOn == null){
update.deactivatedOn = date;
}
const response = await client.execute(update);
const result = response.getResult();
}
}
}
} catch (ex) {
if (ex instanceof IA.Exceptions.ResponseException) {
logger.error("A server response exception was thrown", {
"Class": ex.constructor.name,
"Message": ex.message,
"API Errors": ex.errors,
});
console.log("Failed! " + ex.message);
} else {
logger.error("An exception was thrown", {
"Class": ex.constructor.name,
"Message": ex.message,
});
console.log(ex.name)
}
}
}
class AbstractObject extends IA.Functions.AbstractFunction {
constructor(controlId) {
super(controlId);
this.integrationName = 'technician';
}
}
class UpdateTechnician extends AbstractObject {
constructor(controlId) {
super(controlId);
}
writeXml(xml) {
xml.writeStartElement("function");
xml.writeAttribute("controlid", this.controlId, true);
xml.writeStartElement("update");
xml.writeStartElement(this.integrationName);
xml.writeElement("id", this.id);
xml.writeElement("name", this.name);
xml.writeElement("business_unit", this.business_unit);
xml.writeElement("branch", this.branch);
xml.writeElement("tenant", this.tenant);
xml.writeElement("location", this.location);
xml.writeElement("database_active", this.database_active);
xml.writeElement("deactivated_on", this.deactivatedOn);
xml.writeEndElement(); // test_object
xml.writeEndElement(); // create
xml.writeEndElement(); // function
}
}
I got some help from a developer friend. Here is code:
async function updateTechnicians(location, itechs, stechs) {
let logger = bootstrap.logger();
try {
const client = bootstrap.client(logger);
let sTechMap = new Map();
for (const tech in stechs) {
sTechMap.set(stechs[tech].id.toString(), stechs[tech]);
}
let update = new UpdateTechnician();
for (const tech in itechs) {
if (itechs[tech].location == location) {
let thisTech = sTechMap.get(itechs[tech].servicetitanid);
let updateItem = {};
if (thisTech) {
updateItem.id = itechs[tech].id;
updateItem.name = thisTech.name;
updateItem.database_active = thisTech.active;
if (thisTech.businessUnit != null) {
updateItem.tenant = thisTech.businessUnit.tenant.name;
updateItem.business_unit = thisTech.businessUnit.name;
if (thisTech.businessUnit.name.includes('Phx')) {
updateItem.branch = 'Phoenix';
} else if (thisTech.businessUnit.name.includes('Tuc')) {
updateItem.branch = 'Tucson';
} else if (thisTech.businessUnit.name.includes('Simi')) {
updateItem.branch = 'Simi Valley';
} else if (location == 'NV') {
updateItem.branch = 'Las Vegas';
} else if (location == 'CA') {
updateItem.branch = 'Corona';
}
}
if (itechs[tech].deactivatedOn != null) {
updateItem.deactivatedOn == null;
}
update.arrUpdate.push(updateItem);
} else {
let today = new Date();
let date = (today.getMonth() + 1) + '/' + today.getDate() + '/' + today.getFullYear();
updateItem.id = itechs[tech].id;
updateItem.name = itechs[tech].name;
updateItem.database_active = false;
if (itechs[tech].deactivatedOn == null) {
updateItem.deactivatedOn = date;
}
update.arrUpdate.push(updateItem);
}
}
}
const response = await client.execute(update);
const result = response.getResult();
// console.log(result);
} catch (ex) {
if (ex instanceof IA.Exceptions.ResponseException) {
logger.error("A server response exception was thrown", {
"Class": ex.constructor.name,
"Message": ex.message,
"API Errors": ex.errors,
});
console.log("Failed! " + ex.message);
} else {
logger.error("An exception was thrown", {
"Class": ex.constructor.name,
"Message": ex.message,
});
console.log(ex.name);
}
}
}
class AbstractObject extends IA.Functions.AbstractFunction {
constructor(controlId) {
super(controlId);
this.integrationName = 'technician';
}
}
class UpdateTechnician extends AbstractObject {
constructor(controlId) {
super(controlId);
this.arrUpdate = [];
}
writeXml(xml) {
//console.log(this.arrUpdate);
xml.writeStartElement("function");
xml.writeAttribute("controlid", this.controlId, true);
xml.writeStartElement("update");
for (const i in this.arrUpdate) {
const item = this.arrUpdate[i];
xml.writeStartElement("technician");
xml.writeElement("id", item.id);
xml.writeElement("name", item.name);
xml.writeElement("business_unit", item.business_unit);
xml.writeElement("branch", item.branch);
xml.writeElement("tenant", item.tenant);
xml.writeElement("location", item.location);
xml.writeElement("database_active", item.database_active);
xml.writeElement("deactivated_on", item.deactivatedOn);
xml.writeEndElement();
}
xml.writeEndElement(); // create
xml.writeEndElement(); // function
}
}
As the title suggests, A better coding structure or implementation for my JavaScript below. This checks a ID element values from a form before submitting to a database.
I'm interested to know if I could have reduced the code size/could have implemented reuse of code which will give me some tips for the future!
Thanks.
function validateRunnerID()
{
var runnerID = document.getElementById('RunnerID').value;
if (isNaN(runnerID) || runnerID < 1 || runnerID > 9999)
{
return "RunnerID: Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
function validateEventID()
{
var eventID = document.getElementById('EventID').value;
if (isNaN(eventID) || eventID < 1 || eventID > 9999)
{
return "EventID: Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
function validateDate()
{
var checkDate= /^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/;
var date= document.getElementById('Date');
var tof= date.value.match(checkDate);
return tof? "" : "Date: Enter a Valid Date with parameters: YYYY-MM-DD \n\n";
}
function validateFinishTime()
{
var finishTime = document.getElementById("FinishTime").value;
if (finishTime.match(/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/))
{
return ""
}else{
return "Finish Time: Enter a valid Time with parameters: HH:MM:SS \n\n";
}
}
//
//
function validatePosition()
{
var position = document.getElementById('Position').value;
if (position.length == 0)
{
document.getElementById('Position').value = -1;
return "";
}else{
return "";
}
}
function validateCategoryID()
{
var categoryID = document.getElementById('CategoryID').value;
if (categoryID.length == 0)
{
document.getElementById('CategoryID').value = -1;
return "";
}else{
return "";
}
}
function validateAgeGrade()
{
var ageGrade = document.getElementById('AgeGrade').value;
if (ageGrade.length == 0)
{
document.getElementById('AgeGrade').value = -1;
return "";
}else{
return "";
}
}
function validatePB()
{
var pBest = document.getElementById('PB').value;
if (pBest.length == 0)
{
document.getElementById('PB').value = 0;
return "";
}else{
return "";
}
}
//
//
function validateForm()
{
var result = validateRunnerID() + validateEventID() + validateDate() + validateFinishTime() + validatePosition() + validateCategoryID() + validateAgeGrade() + validatePB();
if ( result == "" )
{
alert("Data Accepted and Submitted \n\n");
return true;
}else{
alert("Please Fix Errors Listed: \n\n" + result);
return false;
}
}
One thing you can do is to accept an elementId as input to your validation functions. This allows to reuse the same logic for different fields.
For example:
function validate4DigitInt(elementId)
{
var value = document.getElementById(elementId).value;
if (isNaN(value) || value < 1 || value > 9999)
{
return elementId + ": Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
Now you can validate both RunnerId and EventId using the same function:
var result="";
result+=validate4DigitInt("RunnerId");
result+=validate4DigitInt("EventId");