Improving if-else with multiple values? - javascript

Is there a better way to do this?
if(cpf.length !== 11 || cpf === "00000000000" || cpf === "11111111111" ||
cpf === "22222222222" || cpf === "33333333333" || cpf === "44444444444" ||
cpf === "55555555555" || cpf === "66666666666" || cpf === "77777777777" ||
cpf === "88888888888" || cpf === "99999999999"){

You could debate if this is better but this is what I like to do in that sort of situation:
// Name this something relevant to the problem
var possibleValues = ["0000000000", ...];
if (possibleValues.includes(cpf)) {
// do stuff
}
or if you're in an environment that doesn't have includes
if (possibleValues.indexOf(cpf) > -1) {
// do stuff
}
Another possibility is using a regular expression:
if (cpf.length === 11 && cpf.match(/^(\d)\1+$/)) {
// do stuff
}
^: Start at the beginning
(\d): Look for a digit and remember it
\1+: Look for the remembered digit repeatedly
$: Hit the end of the string

Using indexOf Something like
var possibleValues = [ "00000000000", "1111111111" ]; //add more values
if ( cpf.length != 11 || possibleValues.indexOf( cpf ) != -1 )
{
//value matching
}

Alternative Ecmascript5 solution using isNaN() and RegExp.text() functions:
if (cpf.length !== 11 || (!isNaN(f = cpf[0]) && new RegExp("^"+ f + "{11}$").test(cpf))) {
// do something
}
isNaN() - to check if we have only numbers(at start)
new RegExp("^"+ f + "{11}$").test(cpf) - to test if we have a sequence of same 11 digits

Related

My function returns the catch all when i'm passing a string that fits the parameters I've tried to set. How to proceed?

I’m running into a wall on the second step of this project. My console test returns as “Card number not recognized” when I put in a Visa or MasterCard number, and the intent is for it to detect which network the card number is from. Any insight you could afford me would be greatly appreciated.
var detectNetwork = function(cardNumber) {
// Note: `cardNumber` will always be a string
var splt = cardNumber.split('');
// The Diner's Club network always starts with a 38 or 39 and is 14 digits long
if ((splt[0] === '3') && (splt[1] === '8' || splt[1] === '9') && (splt.length === 14)) {
return 'Diner\'s Club';
} else if ((splt[0] === '3') && (splt[1] === '4' || splt[1] === '7') && (splt.length === 15)) {
return 'American Express';
} else if ((splt[0] === '4') &&
(splt.length === 13 ||
splt.length === 16 ||
splt.length === 19)) {
return 'Visa';
} else if ((splt[0] === '5') &&
((splt[1] === '1') || (splt[1] === '2') || (splt[1] === '3') ||
(splt[1] === '4') || (splt[1] === '5')) &&
(splt.length === 16)) {
return 'MasterCard';
} else {
return 'Card number not recognized';
}
// The American Express network always starts with a 34 or 37 and is 15 digits long
// Once you've read this, go ahead and try to implement this function, then return to the console.
};
instead of using a bunch of IFs, I would rather to use RegExp so it is easier to follow what you want to achieve.
Additionally to that, before checking the string I also recommend to clean it, so in case you get something like:
1234-1234.1234 1234$1234
it will cleaned and you will get something like:
12341234123412341234
and it is easier to check if it really matches
here you have all my recommendations applied and working, I put an example of each of the cases, along with this you can see that the first 1/2 digits are separated, so you can recognize it better.
const replacer = /[^\d]/g;
const dinnersRegex = /^3(8|9)\d{12}$/;
const americanRegex = /^3(4|7)\d{13}$/;
const visaRegex = /^4(\d{18}|\d{15}|\d{12})$/;
const masterRegex = /^5(1|2|3|4|5)\d{14}$/;
var detectNetwork = function(cardNumber) {
// lets replace all weird characters BUT numbers.
const cleanNumber = cardNumber.replace(replacer, "")
if (dinnersRegex.test(cleanNumber)) {
return 'Diner\'s Club';
} else if (americanRegex.test(cleanNumber)) {
return 'American Express';
} else if (visaRegex.test(cleanNumber)) {
return 'Visa';
} else if (masterRegex.test(cleanNumber)) {
return 'MasterCard';
} else {
return 'Card number not recognized';
}
};
// used some weird symbols to use the cleaner and see if it works.
console.log("diners1:", detectNetwork("38--12-1231-1234-12"))
console.log("diners2:", detectNetwork("39--12-1231-1234-12"))
console.log("american1:", detectNetwork("34 121231 1234 129"))
console.log("american2:", detectNetwork("37 121231 1234 129"))
console.log("visa1:", detectNetwork("4 712.1231.1234.1291.123"))
console.log("visa2:", detectNetwork("4 712123112341298"))
console.log("visa3:", detectNetwork("4 712123112341"))
console.log("master1:", detectNetwork("5 112123112341291"))
console.log("master1:", detectNetwork("5 212123112341291"))
console.log("master1:", detectNetwork("5 312123112341291"))
console.log("master1:", detectNetwork("5 412123112341291"))
console.log("master1:", detectNetwork("5 512123112341291"))
console.log("unrecognized:", detectNetwork("9812311234129"))

JS operator on document.getElementById gives unexpected result

I am using this JS code without any issues:
if(document.getElementById('add_calc_srt_gew').value.length != '' &&
document.getElementById('add_calc_dia_inner').value.length != '' &&
document.getElementById('add_calc_dia_out').value.length != '' &&
document.getElementById('add_breedte').value.length != '') {
// do something }
I need to add one more check. When add_calc_dia_out is larger then add_calc_dia_inner
So I have changed the JS to:
if(document.getElementById('add_calc_srt_gew').value.length != '' &&
document.getElementById('add_calc_dia_inner').value.length != '' &&
document.getElementById('add_calc_dia_out').value.length != '' &&
document.getElementById('add_breedte').value.length != '' &&
(document.getElementById('add_calc_dia_out').value > document.getElementById('add_calc_dia_inner').value)) {
// do something }
But the code that should be triggered is not triggered. Also no errors are shown. What is the correct way to be sure that add_calc_dia_out is larger then add_calc_dia_inner ?
Here is a DRY version
const num = str => isNaN(str) || str.trim() === "" ? 0 : +str;
const srt_gew = num(document.getElementById('add_calc_srt_gew').value),
dia_inner = num(document.getElementById('add_calc_dia_inner').value),
dia_out = num(document.getElementById('add_calc_dia_out').value),
breedte = num(document.getElementById('add_breedte').value);
if (srt_gew && dia_inner && dia_out && breedte && dia_out > dia_inner) { /* do something */ }
You are compare 2 number in string. It will cause unexpected behavior like '9' > '11'. You have to parseInt() them first. Try this:
... && parseInt(document.getElementById('add_calc_dia_out').value) > parseInt(document.getElementById('add_calc_dia_inner').value)) {
Also, you should check if it's a valid number or not before doing the compare:
!Number.isNaN(document.getElementById('add_calc_dia_out').value) && !Number.isNaN(document.getElementById('add_calc_dia_inner').value))

Javascript if clause not working properly

I have the following Javascript/jQuery:
$('#List').keypress(function (e) {
if (e.which == 13) {
var lines = $('#List').val().split('\n');
mylast = lines[lines.length - 1];
mylen = mylast.length;
if ((mylen != 8) || (mylen != 4)) {
lines = lines.slice(lines.length-1);
$('#List').val(lines.join("\n"));
alert(mylen);
return false;
}
return true;
}
});
But it jumps into the code block after if even if length is 4 or 8....
Where is my error?
I want to remove the last line of the textarea if it's not of a given length.
It should not be:
if ((mylen != 8) || (mylen != 4)) {
it should be:
if ((mylen != 8) && (mylen != 4)) {
your way if it was 8 , it was not 4 so it was getting through or if it was 4 it was not 8. you need to check that its not either
This line:
if ((mylen != 8) || (mylen != 4)) {
means "if length is not 8 or length is not 4". So for instance, 4 is not 8, so the condition is true (the second part is never tested, because JavaScript expressions are short-circuited). Similarly, if it's 8, the first part of the expression is false, but the second part (8 != 4) is true, and so the expression is true.
You probably want:
if ((mylen != 8) && (mylen != 4)) {
&& means "and."
Lets examine the case of when mylen is 4.
mylen != 8 //true
mylen != 4 //false
true || false // true
What you probably want is to prevent mylen from being 8 and prevent mylen from being 4:
(mylen != 8) && (mylen != 4)
FWIW, here's a better version of your code:
$('#List').keypress(function (e) {
var lines, last, valid;
if (e.which === 13) {
lines = $(this).val().split('\n');
last = lines.pop();
valid = last.length === 4 || last.length === 8;
if (!valid) {
$(this).val(lines.join("\n"));
e.preventDefault();
}
}
});
it declares all variables as local (never forget the var keyword!)
it uses $(this) instead of repeating the $('#List')
it uses e.preventDefault() instead of returning false
it uses a variable named valid to transport meaning clearer
it uses strict comparison (===)
if the code is part of a form validity check, consider putting it into the submit event handler instead of capturing the Enter key.

Validate CreditCard Number and checked radio button javascript

I have radio buttons radioVisa, and radioMaster. If either one is checked, I need to first check to see which one is selected and then validate that the card number entered is valid. I also need to make sure that only numbers are entered.... I am not allowed to use any regular expression techniques.... If the radioVisa is checked, it seems to work but when I added the code for the radioMaster, if it is checked it does't work.... Can someone tell me what I am doing wrong please....
function isValidCardNumber(num, isVisa, isMaster){
var card = new Array();
if (document.getElementById('radioVisa').checked){
card = isVisa;
}
if (num[0] != '4' || num.length != 16 ){
return false;
} else {
return true;
} else if (document.getElementById('radioMaster').checked){
card = isMaster;
}
if (num[0] != '51' || num[0] != '52' || num[0] != '53' ||
num[0] != '54' || num[0] != '55' || num.length != 16 ){
return false;
} else {
return true;
}
if (num[0] != '51' || num[0] != '52' || num[0] != '53' ||
num[0] != '54' || num[0] != '55' || num.length != 16 )
You can not combine all those numbers.You need to specify individually.
or
var numbers= ["51", "52", "53", "54",55];
var index = numbers.indexOf(num[0]);
It will return -1 if that is not exist otherwise return the index

jQuery: Check if special characters exists in string

I know this question is asked more often here on Stack, but I can't seem to get a straight answer out of the questions already posted.
I need to check if all special characters (except -) are in a string, if so, then give the user an alert.
What I have so far is this:
if($('#Search').val().indexOf('#') == -1 || $('#Search').val().indexOf('#') == -1 || $('#Search').val().indexOf('$') == -1 || $('#Search').val().indexOf('%') == -1 || $('#Search').val().indexOf('^') == -1 || $('#Search').val().indexOf('&') == -1 || $('#Search').val().indexOf('*') == -1 || $('#Search').val().indexOf('(') == -1 || $('#Search').val().indexOf(')') == -1 || $('#Search').val().indexOf('_') == -1 || $('#Search').val().indexOf('\'') == -1 || $('#Search').val().indexOf('\"') == -1 || $('#Search').val().indexOf('\\') == -1 || $('#Search').val().indexOf('|') == -1 || $('#Search').val().indexOf('?') == -1 || $('#Search').val().indexOf('/') == -1 || $('#Search').val().indexOf(':') == -1 || $('#Search').val().indexOf(';') == -1 || $('#Search').val().indexOf('!') == -1 || $('#Search').val().indexOf('~') == -1 || $('#Search').val().indexOf('`') == -1 || $('#Search').val().indexOf(',') == -1 || $('#Search').val().indexOf('.') == -1 || $('#Search').val().indexOf('<') == -1 || $('#Search').val().indexOf('>') == -1 || $('#Search').val().indexOf('{') == -1 || $('#Search').val().indexOf('}') == -1 || $('#Search').val().indexOf('[') == -1 || $('#Search').val().indexOf(']') == -1 || $('#Search').val().indexOf('+') == -1 || $('#Search').val().indexOf('=') == -1)
{
// Code that needs to execute when none of the above is in the string
}
else
{
alert('Your search string contains illegal characters.');
}
But this doesn't seem to work. Can anyone help me on this matter?
If you really want to check for all those special characters, it's easier to use a regular expression:
var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('Your search string contains illegal characters.');
}
The above will only allow strings consisting entirely of characters on the ranges a-z, A-Z, 0-9, plus the hyphen an space characters. A string containing any other character will cause the alert.
var specialChars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
var check = function(string){
for(i = 0; i < specialChars.length;i++){
if(string.indexOf(specialChars[i]) > -1){
return true
}
}
return false;
}
if(check($('#Search').val()) == false){
// Code that needs to execute when none of the above is in the string
}else{
alert('Your search string contains illegal characters.');
}
You could also use the whitelist method -
var str = $('#Search').val();
var regex = /[^\w\s]/gi;
if(regex.test(str) == true) {
alert('Your search string contains illegal characters.');
}
The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.
You are checking whether the string contains all illegal characters. Change the ||s to &&s.

Categories

Resources