wrong error message output in function - javascript

I am trying to validate a Poperty value and down payment. The conditions are as follows:
property value:
Must be present
Must be numeric - positive - whole number
Must be at least 65,000 dollars more that the down payment.
down payment:
Must be present
Must be numeric - positive - whole number
Must be at least 20% of the value of the property (propValue)
My function is (sort of) working. It doesn't pass all the validation tests. If someone can point me in the right direction as to how to improve this it would be greatly appreciated. My 2 functions for the down pay and value:
function propValueValidation(errMessages){
var propValueLength = document.mortgage.propValue.value.length;
var propValueNumber = isNaN(document.mortgage.propValue.value);
var propValue = document.mortgage.propValue.value;
var downPayPlus = document.mortgage.downPay.value + 65000;
if (!propValueLength) {
errMessages += " Property Value is a required field";
return errMessages;
}
else if (typeof propValue === 'number') {
var remainder = (propValue % 1);
if(remainder != 0){
errMessages += "Property Value must be a positive whole number";
return errMessages;
}
}
else if (propValue < downPayPlus){
errMessages += "Property Value must be at least 65,000 greater than the down payment";
return errMessages;
}
return errMessages;
}
//validate down pay
function downPayValidation(errMessages){
var downPayLength = document.mortgage.downPay.value.length;
var downPay = document.mortgage.downPay.value;
var propValueMin = document.mortgage.propValue.value * 0.2;
if (!downPayLength) {
errMessages += "Down Payment is a required field";
return errMessages;
}
else if (typeof downPay === 'number') {
var remainder = (downPay % 1);
if(remainder != 0){
errMessages += "Down Payment must be a positive whole number";
return errMessages;
}
}
else if (downPay < propValueMin){
errMessages +="Down Payment must be at least 20% of the property value";
return errMessages;
}
return errMessages;
}
HTML:
<label class="label">Property Value </label>
<input type="text" name="propValue" id="propValue" size="7" maxlength="6" >
<br>
<label class="label">Down Payment </label>
<input type="text" name="downPay" id="downPay" size="7" maxlength="6" >
when downpay is "1nn1" it will still submit the form for example. Thanks!

you can use parseInt() to confirm its a number.
var tempVal = document.mortgage.propValue.value;
var propValue = parseInt(tempVal); // this will try to extract an integer from tempVal
if (tempVal != propValue.toString()) // if true, there were non-number chars or value is NaN
{
errMessages += "Bad value, please enter an integer";
}

You should not use isNaN on string values (which input values are). Instead first convert such a string to number with Number() (or parseFloat, but Number will require the whole of the input to parse as number, while parseFloat or parseInt will accept strings that start with a number). Then call isNaN on that.
There is also a problem with the if else logic, because you have one branch for numeric data (where it will never get, because the value property of input elements is always a string), and an else on that to compare the amount with another amount. Yet for that last test the value must be numeric. So that test is in the wrong place.
Here is your first function's code with some alterations made:
function propValueValidation(errMessages){
var propValue = document.mortgage.propValue.value;
var propValueNumber = Number(propValue);
var downPayPlus = propValueNumber + 65000;
var genericMsg = ' property value was provided. Please provide a positive' +
' whole number, at least 65,000 greater than the down payment.\n';
if (!propValue.length) {
errMessages += 'No' + genericMsg;
} else if (isNaN(propValueNumber)) {
errMessages += 'A non-numerical' + genericMsg;
} else if (propValueNumber % 1) {
errMessages += 'A fractional' + genericMsg;
} else if (propValueNumber < downPayPlus){
errMessages += 'A too small' + genericMsg;
}
return errMessages;
}

Related

How can I create a credit card validator using Luhn's algorithm?

I am trying to create a simple credit card validator using Luhn's algorithm. If the check digit matches the last inputted number, then it should alert the user that it is valid. Else, say that it isn't valid. Currently, I am getting an error with my sum (total) coming up as NaN. I assume that is the only problem with the code.
<input type="number" id="creditCard" placeholder="0000 0000 0000 0000">
<input type="submit" id="checkButton" value="CHECK VALIDITY" onclick="checkNumber()">
function checkNumber() {
let number = document.getElementById("creditCard").value;
let multiplier = "212121212121212";
let multipliedNumber;
let multipliedString;
if (number.length != 16) {
alert("Please enter a Credit Card number that is 16 digits in length.");
} else {
for (count = 0; count < number.length - 1; count++) {
multipliedNumber = number[count] * multiplier[count];
console.log(multipliedNumber);
if (multipliedNumber > 9) {
multipliedNumber = multipliedNumber[0] + multipliedNumber[1];
multipliedString = multipliedString + multipliedNumber;
} else {
multipliedString = multipliedString + multipliedNumber;
}
}
console.log(multipliedString);
let checkDigit = 10 - (multipliedString % 10);
if (checkDigit == number[15]) {
alert(`${number} is a valid Credit Card number.`);
} else {
alert(`${number} is not a valid Credit Card number.`);
}
}
}
There are several issues:
multipliedNumber is a product, so it is a number type. Therefore accessing properties like [0] or [1] on it, will just evaluate to undefined. Either turn that value to string first, or (better) use arithmetic to extract the two digits:
multipliedNumber = multipliedNumber % 10 + Math.floor(multipliedNumber/10);
multipliedString is not initialised, so adding things to it will not give the desired outcome. Secondly, you define it as a string, but it should be a number, as with Luhn's algorithm you are supposed to sum up the resulting digits, not concatenate them. So initialise a variable like this:
sum = 0;
... and use it like you did -- although you could benefit from the += operator, and since the operation is the same for both cases, you can do it outside of the if..else blocks.
The calculation of the check digit is wrong when the modulo operation evaluates to 0: 10 - (multipliedString % 10) then returns 10, but in that case the check digit is supposed to be 0. It is much easier to just treat that last digit also in the loop and then check that you have reached a multiple of 10. This is also how the algorithm is explained on Wikipedia
Corrected version:
function checkNumber() {
let number = document.getElementById("creditCard").value;
let multiplier = "2121212121212121"; // One more character added...
let multipliedNumber;
let sum = 0 // Initialise it as a number.
if (number.length != 16) {
console.log("Please enter a Credit Card number that is 16 digits in length.");
} else {
for (count = 0; count < number.length; count++) { // Include last digit in loop
multipliedNumber = number[count] * multiplier[count];
if (multipliedNumber > 9) {
// Use arithmetic to add the two digits
multipliedNumber = multipliedNumber % 10 + Math.floor(multipliedNumber/10);
}
sum += multipliedNumber;
}
let check = sum % 10; // Simpler now because all digits were processed
if (check == 0) { // Sum is multiple of 10
console.log(`${number} is a valid Credit Card number.`);
} else {
console.log(`${number} is not a valid Credit Card number.`);
}
}
}
<input type="number" id="creditCard" placeholder="0000 0000 0000 0000">
<input type="submit" id="checkButton" value="CHECK VALIDITY" onclick="checkNumber()">

Why does if statement not work and make my element disappear using display: none?

I am building a tip calculator and I couldn't make the if statement in my function work it just skips to calculating.
function calculate() {
var bill = parseInt(document.getElementById("bill").value);
var tip = parseInt(document.getElementById("tip").value) * .01;
var persons = parseInt(document.getElementById("persons").value);
if (bill == "" || tip == "") {
alert("Please enter value");
return;
};
if (persons == "" || persons <= 1) {
persons = 1;
document.getElementById("perPerson").style.display = "none";
} else {
}
let totalTipPer = (bill * tip) / persons;
let totalPer = (bill + (tip * 100)) / persons;
let totalTip = bill * tip;
let total = bill + (tip * 100);
totalTipPer = totalTipPer.toFixed(2);
totalPer = totalPer.toFixed(2);
total = total.toFixed(2);
totalTip = totalTip.toFixed(2);
document.getElementById("total-tip/person").innerHTML = totalTipPer;
document.getElementById("total-price/person").innerHTML = totalPer;
document.getElementById("total-tip").innerHTML = totalTip;
document.getElementById("total-price").innerHTML = total;
}
document.getElementById("calculate").onclick = function () {
calculate();
document.getElementById('results').style.display = 'block';
}
I expect the div encapsulating Tip Amount per person and total per person and to not appear when the input value of persons is empty.
Function parseInt returns 'An integer number parsed from the given string. If the first character cannot be converted to a number, NaN is returned.'
if you rpovide an empty value ('') it will return
NaN which is not equal to anything, even itself.
there are several ways to fix this:
check if it is a NaN with Number.isNaN(var)
use an intermediate value like var personsValue and check if it is equal to empty string ''.
use Hybrid suggested solution and assign a 0
value for falsy value('', undefined, n
ull etc...)
The issue is that persons becomes NaN, since if the value is left blank, "" becomes NaN when it is run through parseInt().
The way to fix this is by defaulting it to 0 if the field is left blank.
var persons = parseInt(document.getElementById("persons").value || 0);
as others pointed out parseInt is returning NaN if the field is blank, but this will also happen if the user inputs $5.00 for example.
Here's one way to make sure the value can be converted to a number before doing so.
// This function determines if a JavaScript String can be converted into a number
function is_numeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function calculate() {
// first put the input values into separate variables
billValue = document.getElementById("bill").value;
tipValue = document.getElementById("tip").value;
personsValue = document.getElementById("persons").value;
// use the is_numeric() function above to check if the values can be converted to numeric
if (!is_numeric(billValue) || !is_numeric(tipValue)) {
alert("Please enter values for bill and tip");
return;
}
// the rest of your code here
}
Hope this helps.

not getting the right output in simple code

I'm working on a small exercise that should print all the odd numbers when a button is clicked. An error is shown when you don't fill in a number etc. When I put a number between 0 - 50, I will get the error saying "Not a number". Can someone help me with this little problem?
I don't know if the problem is with my output box in html, my tags or if there is something wrong with the if/ else statement.
let inputGetal = document.getElementById("getalInput");
//inputNumber
let genereerButton = document.getElementById("genereerButton"); //generateButton
let outputVenster = document.getElementById("outputVenster");
//outputWindow
let getal = inputGetal.value;
let onevenGetallen = () => {
if(typeof getal == "number" && (getal >= 0 || getal <= 50)) {`enter code here`
for (let i = 1; i < getal; i + 2) {
outputVenster.value += i + '<tab>';
}
} else {
outputVenster.value += "Geen goed getal" //not the right number
}
};
genereerButton.addEventListener("click", onevenGetallen);
I want to see all the odd numbers starting from 1 untill the input number has been reached.
You need to move to get the number from the input inside of the function, otherwise you get the original value, not the actual.
You need to convert the string to an integer number by using parseInt with a radix of 10.
Take the check with a logical AND &&, because both conditions have to be true.
Finally you need an addition assignment += in the final-expression part of the for statement.
let inputGetal = document.getElementById("getalInput"),
genereerButton = document.getElementById("genereerButton"),
outputVenster = document.getElementById("outputVenster"),
onevenGetallen = () => {
let getal = parseInt(inputGetal.value, 10); // get value, take integer number
if (getal >= 0 && getal <= 50) { // logical AND &&
outputVenster.value = ''; // empty output
for (let i = 1; i <= getal; i += 2) { // comparison <=, addition assignment
outputVenster.value += i + ' '; // take space as separator
}
} else {
outputVenster.value = "Geen goed getal";
}
};
genereerButton.addEventListener("click", onevenGetallen);
<input type="text" id="getalInput"> <input type="text" id="outputVenster"> <button id="genereerButton">go</button>

Javascript validation using isNaN and !==0

I'm new to javascript and I have input boxes that must not allow a zero value or non-numbers. I originaly tried to create a regular expression but I couldn't seem to get any of them to work correctly. I then came up with the following solution but it seems to only work some of the time. I think my if statements are jacked up. Any help with the code as far as making it better would be greatly appreciated.
HTML:
<input name="payrate" id="payrate"></td>
<input name="hours" id="hours" value="0" onclick="dollars()" onchange="dollars()"></td>
Javascript:
function dollars(){
var rate = 0;
rate= document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!isNaN(hours)){
// !isNan - not a Number
// !rate == 0 - value not equal to 0
if (!isNaN(rate) && !rate == 0) {
//round value of payrate to 2 decimal places
var adjrate = Math.round(rate*100)/100;
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
}else{
alert("You entered an invalid rate.\n"+
"Please enter your hourly pay.\n"+
"Example: 8.87 value entered: " + rate);
rate = "";
disableRadio();
resetForm();
}
}else{
alert("You entered invalid or empty hours.\n"+
"Please enter the number of hours worked.\n"+ hours);
hours = "";
disableRadio();
resetForm();
}
}
There is no need to check two times for isNaN. Try to simplify the conditions like this:
function dollars(){
var rate = 0;
rate= document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!isNaN(hours)){
// !isNan - not a Number
// !rate == 0 - value not equal to 0
if (rate > 0) {
//round value of payrate to 2 decimal places
var adjrate = Math.round(rate*100)/100;
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
}else{
alert("You entered an invalid rate.\n"+
"Please enter your hourly pay.\n"+
"Example: 8.87 value entered: " + rate);
rate = "";
disableRadio();
resetForm();
}
}else{
alert("You entered invalid or empty hours.\n"+
"Please enter the number of hours worked.\n"+ hours);
hours = "";
disableRadio();
resetForm();
}
}
You can use <input type="number" min="0.01" step="0.01" value="0.01"> element. See doc. So you will be sure that value rate and hours will be an integer.
As example - you should be able to add whatever you need in this I have commented out some of the additional function calls that were not included - but you should be able to go from here.
<input name="payrate" id="payrate">
<input name="hours" id="hours" value="0" onclick="dollar()" onkeyup="dollar()">
<script>
function dollar(){
var rate = document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!hours || isNaN(hours)){
alert('hours must be a numeric value greater than zeo');
// disableRadio();
// resetForm();
return false;
}
if (!rate || isNaN(rate)) {
alert('rate must be a numeric value greater than zeo');
//disableRadio();
//resetForm();
return false;
}
var adjrate = Math.round(rate*100)/100;
/**
* commented out for example since not included in example code -
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
*/
}
</script>

validating phone number in Javascript with hyphens

ok So I've tried to validate a phone number script for the past 2 hours but I can't seem to figure out why this isn't working. the Maximum length is 12 and I've already got an if statement for that, that works.
the format would have to be : nnn-nnn-nnnn
var tele = document.pizza.field03; //store phone number
var fone = tele.value //store values of variable tele in fone
var acode = "";
var midnum = "";
var lasnum = "";
var hyphen = "";
var hyphen2 ="";
acode=fone.substr(0,3);
hyphen=fone.substr(3,4);
midnum=fone.substr(4,7);
hyphen2=fone.substr(7,8);
lasnum=fone.substr(8);
else if (isNaN(acode) )
{
errMessages += "<li>Please use integer numbers only</li>\n";
errMessages += "<li>ex: 1 2 3 4 5 </li>\n";
}
else if (isNaN(midnum) )
{
errMessages += "<li>Please use integer numbers only</li>\n";
errMessages += "<li>ex: 1 2 3 4 5 </li>\n";
}
else if (isNaN(lasnum) )
{
errMessages += "<li>Please use integer numbers only</li>\n";
errMessages += "<li>ex: 1 2 3 4 5 </li>\n";
}
EDIT*
else if (hyphen.indexOf('-') ==-1) //checking for hyphen
{
errMessages += "<li>You need a hyphen after the area code</li>\n"
errMessages += "<li>ex: areacode-nnn-nnn</li>\n"
}
else if (hyphen2.indexOf('-') ==-1)
{
errMessages += "<li>You need a hyphen after the middle 3 digits</li>\n";
errMessages += "<li>ex: 416-mid-1234</li>\n";
}
what happens is whether I use digits or letters it'll keep popping up the error window.
I want to learn how to do this without using RegEx if possible.
Thank you.
acode=fone.substr(0,3);
hyphen=fone.substr(3,4);
midnum=fone.substr(4,7);
hyphen2=fone.substr(7,8);
lasnum=fone.substr(8);
The second parameter specifies the length of the string taken, not the "end position". (See reference)
Your variables come out with the values 'nnn', '-nnn', 'nnn-nnnn', '-nnnn' and 'nnnn'.
acode=fone.substr(0,3);
hyphen=fone.substr(3,1);
midnum=fone.substr(4,3);
hyphen2=fone.substr(7,1);
lasnum=fone.substr(8);
The syntax of substr is string.substr(start,length).
You, however, seem to be calling it with string.substr(start,end).
See here for more details

Categories

Resources