Validate CreditCard Number and checked radio button javascript - 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

Related

Javascript filtering with multiple parameters

I need to filter my content with multiple parameters that I am taking from fields. The fields could also be empty, so I need to get all the values that are not empty. And filter by those.
What is the best way to achieve this without making a lot of if and else if conditions like this:
if (a !== '' && b !== '' && c !== '' && d !== '' && e !== ''){
// none is empty, filter by a & b & c & d & e
}
else if ( b !== '' && c !== '' && d !== '' && e !== ''){
// a is empty, filter by b & c & d & e
}
else if ( a !== '' && c !== '' && d !== '' && e !== ''){
// b is empty, filter by a & c & d & e
}
else if ( b !== '' && a !== '' && d !== '' && e !== ''){
}
else if ( b !== '' && c !== '' && a !== '' && e !== ''){
}
else if ( b !== '' && c !== '' && d !== '' && a !== ''){
}
else if ( c !== '' && d !== '' && e !== ''){
}
else if ( b !== '' && d !== '' && e !== ''){
}
else if ( b !== '' && c !== '' && e !== ''){
}
else if ( b !== '' && c !== '' && d !== ''){
}
else if ( a !== '' && d !== '' && e !== ''){
}
and so on...
Alternatively, how can I get all the unique possible combination of these 5 letters?
Edit ::
The actual code would look something like this
//a/b/c take value of dropdown items, that match with data on an object
if (a != '' && b != '' && c != '') {
for (const i in ParticipationList.TaskMetadata) {
if (ParticipationList.TaskMetadata[i].attendance == a && ParticipationList.TaskMetadata[i].monitoring_status == b && ParticipationList.TaskMetadata[i].monitoring_status == c) {
filteredaudience[i] = { ['id']: i }
}
console.log(filteredaudience)
// get all the items that match with the object properties
}
}
So if a or b or c is empty, I can't still make the same call, as it would not match anything on the object.
The logic:
Since javascript has short-circuit evaluation, we'll just use a bunch of conditions in the format:
field === "" || (condition to filter using field)
Because of said "short-circuiting", the right side part will only be reached if the field is not empty (i.e. if the left side is false because field !== ""). However, if the field is empty then field === "" will be true and the right side part won't be reached and the whole condition will yield true resulting in the filtering for this field to be skipped.
Multiple conditions should be joined together by the logical && operator and each one of those conditions should be wrapped in parenthesis () because the operator && is higher in precedence than the || operator.
If the data to filter is an array:
For arrays, just use the conditions as the value returned from the callback of filter like so:
let filteredData = data.filter(item =>
(a === "" || (condition for field 'a' against 'item'))
&&
(b === "" || (condition for field 'b' against 'item'))
&&
(c === "" || (condition for field 'c' against 'item'))
&&
(d === "" || (condition for field 'd' against 'item'))
&&
(e === "" || (condition for field 'e' against 'item'))
);
If the data to filter is an object:
In case the data is an object and you can't use filter like above, you can still use the same logic, you just have to use the conditions inside if like so:
let filteredaudience = {};
for (const i in ParticipationList.TaskMetadata) {
if ((a === "" || ParticipationList.TaskMetadata[i].attendance === a)
&& (b === "" || ParticipationList.TaskMetadata[i].monitoring_status === b)
&& (c === "" || ParticipationList.TaskMetadata[i].monitoring_status === c)
&& (d === "" || ParticipationList.TaskMetadata[i].?????????? === d)
&& (e === "" || ParticipationList.TaskMetadata[i].?????????? === e)) {
filteredaudience[i] = { id: i };
}
}
Depending on how the actual filtering process works, it might be possible to incrementally filter your result instead of doing it simultaneously.
For example, if your data is an array, you might write:
let data = ...;
if (a != '') {
data = data.filter(elem => checkForA(a, elem));
}
if (b != '') {
data = data.filter(elem => checkForB(b, elem));
}
...
Maybe you can also incrementally augment the filter object itself and THEN apply the built filter.
Please enter more details ...
For now, what I understood was that you want to get all the
values that are not empty.
for this:
let allElements = [a, b, c, d, e]
let notEmpty = []
allElements.forEach(element => {
if (element !== '')
notEmpty.push(element)
});
console.log(notEmpty)
A common mistake for new developers is to create long, complicated and repetative if statements with tons of && and || symbols or long strings of if/else if
Instead of this, write a simple search predicate. This is a function which takes some parameters, and reduces them to either true or false.
Within said function, run each filter one at a time. As soon as one fails, return false.
var data = [
{ colour : "red", weight : 2, name : "Example 1"},
{ colour : "orange", weight : 15, name : "Example 2"},
{ colour : "yellow", weight : 10, name : "Test 1"},
{ colour : "green", weight : 24, name : "Test 2"}
];
console.log(search(data, "red", [], ""));
console.log(search(data, "", [5,20], ""));
console.log(search(data, "", [], "Test"));
function search(data, colour, weights, name) {
return data.filter(row=>testRow(colour, weights, name, row));
}
// much easier to read.
function testRow(colourFilter, weightFilter, nameSearchFilter, row) {
// run each filter one at a time. If any fail, "short circuit" out.
if (colourFilter != "" && row.colour == colourFilter) {
return false;
}
// sometimes, a double if statemnt is easier to read.
if (weightFilter.length > 0) {
if (row.weight < weightFilter[0] || row.weight > weightFilter[1]) {
return false;
}
}
// sometimes, the actual rule is a bit complex.
if (nameSearchFilter != "") {
if (row.name.indexOf(nameSearchFilter) < 0) {
return false;
}
}
// we survived all filters.
return true;
}

Improving if-else with multiple values?

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

javascript multidimensional array is valid

I have an array that looks kind of like this memory[indexGroup][indexItem]. How can I check if that is valid, in other words if it would work when using console.log and getting a value back, not null, undefined or other non values. Empty, 0 and false are valid. These don't give errors.
This is what I ended up with (seems to work) but it's a mess:
function hasMemory() {
if( typeof memory === 'undefined') return;
if( typeof memory[indexGroup] === 'undefined') return;
if( memory[indexGroup] === null ) return;
if( typeof memory[indexGroup][indexItem] === 'undefined') return;
if( memory[indexGroup][indexItem] === null) return;
if( memory[indexGroup][indexItem] !== true ) return;
return true;
}
Scenarios
memory is not set
memory[indexGroup] is not set
memory[indexGroup][indexItem] is not set
Then it should just return but if the full multidimensional array is valid, it should return true.
Is there a shorter/better/safer ways to check this?
function hasMemory() {
return memory && memory[indexGroup] && memory[indexGroup][indexItem]
}
To handle the case where memory[indexGroup][indexItem] is 0 or false, based on
undefined == null
null == undefined
you can add to condition memory[indexGroup][indexItem]!=null
You can check for both null and undefined simultaneously by performing a loose check against null but will not work for 0 or false.
var u = undefined;
var n = null;
var z = 0;
var f = false;
console.log(u == null);
console.log(n == null);
console.log(z == null);
console.log(f == null);
Using that, here's a shorter way of approaching this:
function hasMemory() {
return memory &&
memory[indexGroup] != null &&
memory[indexGroup][indexItem] != null;
}

Javascript multiple statements in a single if not working

I have 20 divs, each one with a speficif class, so I select it and check if is 1 of the 4 'special ones'.
The main issue is that the following code is supposed to work...
$('.cbp-ig-grid li, .cbp-ig-grid li a span object').on('click', function () {
/* Variables Definition */
var item = $(this).find('span').attr('class').split(' ')[1]
}
if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4')){
// Always enters here!
}else{
// Never enters here :( (I need to enter here for the 4 cases in the if statement)
}
but when I do for just one ... it works!
if(item != 'item1'){
// do stuff
}else{
// do other stuff
}
I don't know what I'm doing wrong, please any help will be useful
Consider your if statement:
if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4')){
}
What that is saying is that if ANY of these conditions are true, the if condition is met and it will execute the if block.
Let's say the item is "item2" now the first expression of your if statement is met as it's not item1 so that part is true. thus it executes the block.
What you want is: &&
if((item != 'item1') && (item != 'item2') && (item != 'item3') && (item != 'item4')){
//when it's not the special case.
}
else
{
//the 4 special cases.
}
if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4')){
No chance to go into the else here... item is always different from one or the other.
.hasClass() is your best friend. https://api.jquery.com/hasclass/
$('.cbp-ig-grid li, .cbp-ig-grid li a span object').on('click', function () {
/* Variables Definition */
var item = $(this).find('span');
switch(true) {
case item.hasClass('item1'):
// item 1
break;
case item.hasClass('item2'):
// item 2
break;
case item.hasClass('item3'):
// item 3
break;
case item.hasClass('item4'):
// item 4
break;
default:
// other stuff
}
});
Let's make it simple
if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4'))
Let's test it:
1:
item = 'item1':
false || true || true || true
that equals to true; because false || true = true
2:
item = 'theGreatOldOnes'
true || true || true || true - that equal to true
Both are true! That means that your expression is flawed - it doesn't make difference between 'special class' and any 'nonspecial class'
To make it understand difference between 'special' and 'not special' you need to use:
if((item != 'item1') && (item != 'item2') && (item != 'item3') && (item != 'item4'))
Or
if((item === 'item1') || (item === 'item2') || (item === 'item3') || (item === 'item4'))
You can do testing with 'item1' and 'theGreatOldOnes' to get a better grip on those things ^ ^

Why is the 'o' is true? Javascript(Angular)

Help me please, I'm trying to make a rule for the little game and there is the problem.
I'm creating winning combination and say if the cell && cell+1 && cell+2 == to 'X' then you win, but when between two "X"s presents "o" it also says that "X" wins. Why? Please see my code and the game example on link a the bottom.
this.rezult = function(){
this.arr2.forEach(function(arr, i, innerArr){
arr.forEach(function(val, j){
var wincomb = innerArr[i][j] && innerArr[i][j+1] && innerArr[i][j+2];
var wincomb2 = innerArr[i][j] && innerArr[i+1][j] && innerArr[i+2][j];
var wincomb3 = innerArr[i][j] && innerArr[i+1][j+1] && innerArr[i+2][j+2];
console.log(wincomb == "X" && innerArr[i][j] !== "o");
// console.log(innerArr);
// THE RULE
if(wincomb == "X"){
alert(' X wins!');
}
});
});
};
Link to JSFiddle
In JavaScript, the && operator has interesting behavior with non-boolean values.
If the left-side of && is "truthy", the result is the right-side.
If the left-side of && is "falsey", the result is the left-side.
All non-empty strings are "truthy".
So, consider these examples:
("A" && "B" && "C") === "C"
("" && "B" && "C") === ""
(0 && "B" && "C") === 0
("X" && "X" && "O") === "O"
("O" && "O" && "X") === "X"
By the looks of it, you're trying to check if all 3 values are equal. You shouldn't use && for that, you should use === for that.
At the risk of doing your homework for you ;) here's a good way to do this:
function areTheSame(a,b,c) {
return a === b && b === c;
}
var down = areTheSame(innerArr[i][j], innerArr[i][j+1], innerArr[i][j+2]);
var across = areTheSame(innerArr[i][j], innerArr[i+1][j], innerArr[i+2][j]);
var diagonal = areTheSame(innerArr[i][j], innerArr[i+1][j+1], innerArr[i+2][j+2]);
if (down || across || diagonal) {
var winner = innerArr[i][j];
alert( winner + " wins!");
}

Categories

Resources