Javascript switch statement with wildcard? - javascript

If my javascript ajaxes away to my server and returns an ID of 49 in the plain text format of [49] is there a way in which i an do something like this... (i have tested and doesnt work)
switch(data)
{
case '[*]':
(..etc.)
break;
}
Where the wildcard is the * and i want to make sure it is enclosed within two square parenthesis?
Because i need to check that there wasnt another word returned like error and i am reserving the default for unexpected errors, any ideas? :) Thanks!

You can do a switch on true explicitely, which will use evaluation on each case statement.
switch (true) {
case ((/^\[\d+\]$/).test(data)):
//matches data;
break;
case (data == "something else"):
//...
break;
default:
//...
}
However, if you have less than say 4-5 cases, it would be better to use if/else if/else if/else blocks.
if ((/^\[\d+\]$/).test(data)) {
//matches data;
} else if (data == "something else") {
//...
} else {
//...
}
I usually do some error trapping in my response methods for service/rest calls so that I almost always return a proper json with an error property if there is an error.
try {
if (response.responseText.indexOf("<html") >= 0) {
throw response.responseText;
}
var data = JSON.parse(response.responseText);
if (data.error)
throw data.error;
//handle response data object.
if ((/^\[\d+\]$/).test(data)) {
//matches data;
} else if (data == "something else") {
//...
} else {
//...
}
} catch(err) {
if (err && err.message) {
//use err.message
} else if (err && err.toString().indexOf("<html") >= 0) {
//handle error text
}
}

You could create a list of patterns and associated callbacks and do a simple loop and check for matches. For example:
var patterns = [];
function myCallback(){ document.write('myCallback!'); }
function myOtherCallback(){ document.write('myOtherCallback!'); }
function myLastCallback(){ document.write('You will never see me!'); }
patterns.push({'pattern':new RegExp(/\[.+\]/),'callback': myCallback});
patterns.push({'pattern':new RegExp(/.+/),'callback':myOtherCallback});
patterns.push({'pattern':new RegExp(/A-Z{3}/),'callback':myLastCallback});
var f = "[49]";
for(var i=0;i<patterns.length;i++){
if(patterns[i].pattern.test(f)){
patterns[i].callback();
}
}
Which outputs the following:
myCallback!myOtherCallback!

You could try to use if else and regex for matching wildcard patterns.
Assuming data = "[49]"; or any digits inside brackets.
if(/\[\d+\]/.test(data)){
//do something
}else{
//default
}

Short answer: No, switch/case can't handle wildcard.
You should probably do some preprocessing/sanity checking before entering the switch, or simply discard it completely since it's more appropriate for specific case scenarios rather than processing streamlined data. Regexp will serve you better here.

Related

how to handle null session in java script

Is there a way to get out of this error. I know it is null but i already put try catch in it why its still showing error and the condition if it is null but the error still showing that my session is null.
here's my code:
try {
if ('<%=Session["Selected"].ToString()%>' == null) {
loadTimesheetgrid();
}
else {
if ('<%=Session["Selected"].ToString()%>' == 'More Than 60 Hrs') {
//call the script you will make for morethan 60 hrs
}
else {
loadTimesheetgrid();
}
}
}
catch (error) {
loadTimesheetgrid();
}
Error showing:
System.NullReferenceException: Object reference not set to an instance
of an object.
If your session value is null it will fail to convert it while .ToString()
So better you first check whether it is null or it has some value, if it has then only try to convert it into string.
if ('<%=Session["Selected"]%>' != null)
{
if ('<%=Session["Selected"].ToString()%>' == 'More Than 60 Hrs')
{
//call the script you will make for morethan 60 hrs
}
else {
loadTimesheetgrid();
}
}
else {
loadTimesheetgrid();
}
I would suggest you not to place try and catch blocks in your view file as sometimes if it fails it loads partial html elements and you may face some alignment issues. However it is your choice to wrap your code in try and catch blocks.
try
{
if ('<%=Session["Selected"]%>' != null)
{
if ('<%=Session["Selected"].ToString()%>' == 'More Than 60 Hrs')
{
//call the script you will make for morethan 60 hrs
}
else {
loadTimesheetgrid();
}
}
else {
loadTimesheetgrid();
}
}
catch(error)
{
loadTimesheetgrid();
}
I'm going to assume that you're using ASP.Net given your post history.
With regard to your question, there's two issues here. Firstly the Session["Selected"] is null on the server side so calling ToString() on that is the cause of your error. If you're using C#6 then you can use the null coalescing operator to return a string instead. If not, then you would need a separate if condition.
Secondly you need to compare the value to an empty string in your client side JS, as '' will never equal null.
Here's a full example:
try {
if ('<%= (Session["Selected"] ?? "").ToString() %>' === '') {
loadTimesheetgrid();
} else {
if ('<%= (Session["Selected"] ?? "").ToString() %>' === 'More Than 60 Hrs') {
//call the script you will make for morethan 60 hrs
} else {
loadTimesheetgrid();
}
}
} catch (error) {
loadTimesheetgrid();
}
Depdending on your use case you may want to consider providing the session value to the View using a ViewModel, to DRY this up a little.

IMacro JavaScript; Loop on IF else statement

for(var i=0;i<1;i++)
{
iimPlay(macro_var)
var extract=iimGetLastExtract();
if(extract.toLowerCase()=="incorrect security code entered!")
{
iimDisplay("wrong")
}
else
{
iimDisplay("right")
}
}
That's my imacro code (Javascript File)
If i get wrong how i do get it to try again until it reaches right?
Supposing you don't want to wait between executions, there are a couple of ways you could do this. The quickest one would be:
while(true) {
iimPlay(macro_var);
var extract = iimGetLastExtract();
if (extract.toLowerCase() == "incorrect security code entered!") {
iimDisplay("wrong");
continue;
} else {
iimDisplay("right");
break;
}
}
In this way, when the extracted value is wrong you restart the loop. If instead it's right, you break out of the loop.

How to check if eval returns nothing in JS

If I want to check if an eval function returns nothing, how do I do it?
I tried to do something like:
if (eval("iwuoinuvwoienvuwope") == "") {
// Do something
alert("Oh NO!");
}
But when I do like that nothing happends.
Here is my full code:
function calc() {
var cal = prompt("Your math....", "1 + 1");
if (cal == null) {
alert("If you don't have a math problem you can gtfo!");
} else if (cal == false) {
alert("If you don't have a math problem you can gtfo!");
}
/* Here I Check if eval is empty */
/* Here it doesn't work */
else if (eval(cal) == "") {
alert("Could you be more specific");
}
/* */
else {
alert("The answer is " + eval(cal));
}
}
<button onclick="calc();">Calculator</button>
eval(code) returns "the completion value of evaluating the given code. If the completion value is empty, undefined is returned." MDN
In your case, a valid math expression returns a Number. Thus you would have to check for typeof result == "Number". If you want to exclude NaN, Infinity and the like, perform additional checks e.g. by isFinite(result).
If you are trying to build a calculator, you should either be expecting a response, an exception or null.
try {
if (r === undefined) {
} else {
// handle response
}
} catch (error) {
// invalid
}
Validating whether it's a Number, and if the mathematical formula is valid will help you identity possible error outputs.

Returning true or false from javascript function

I'm doing a regex check on a string within a function:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/,
matches = regex.exec(listOfZipCodes);
if (regex.exec(listOfZipCodes) === null) {
console.log('validation failed');
return false;
} else {
console.log('validation passed');
return true;
}
}
The regex is correctly detecting a valid/invalid list of zip codes.
I'm calling the function with this:
console.log('zip code: ' + listOfZipCodes);
if (ValidateZipCodeString(listOfZipCodes)) {
$tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
console.log('validate function returned true');
}
The problem is that the above if/else goes to the else clause, when the console output within the validation function shows "validation failed". So I must not be calling that function right.
What's the correct way to do what I'm trying to do?
Your function could be greatly simplified to:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/;
if (regex.test(listOfZipCodes)) {
console.log('validation passed');
return true;
} else {
console.log('validation failed');
return false;
}
}
...or:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/;
return regex.test(listOfZipCodes);
}
...or even just:
function ValidateZipCodeString(listOfZipCodes) {
return /^([, ]*\d{5})+[, ]*$/.test(listOfZipCodes);
}
...but the real issue (as Teemu points out) is not in your function, but in the use of it. Your function answers the question, "Is this a valid zip code string?", but your use of it is saying, "Say this is invalid if my function says it is."
Actually your validation function doesn't return true when validation fails. You just check the value incorrectly, it should be:
if (!ValidateZipCodeString(listOfZipCodes)) {
$tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
console.log('validate function returned true');
}
Others correctly pointed out that you just had your tests in the wrong order. However, and more importantly, your regex is incorrect, as it will for example return true for "1234567890".
Here is a suggestion:
function ValidateZipCodeString(listOfZipCodes) {
return /^\d{5}(\s*,\s*\d{5})*$/.test(listOfZipCodes);
}

Using switch statement to evaluate regex in javascript

I'm trying to manage my if statements into a switch statement to evaluate regex, but I don't know how I can go about it. I tried many possibilities but cannot do it. See code below, is it right?:
var username = $('input.username'),
phone = $('input.phone'),
numRegex = /^[0-9]/i,
alphaRegex = /^[a-zA-Z]/i,
usernameVal = username.val(),
phoneVal = phone.val();
switch (phoneVal) {
case numRegex.test(phoneVal):
console.log('Only digits please.');
break;
default:
console.log('It\'s all good.');
}
Many thanks.
I think this kind of defeats the point of the switch statement having the conditions in the case statements. It's intent is to test multiple outputs given a single input.
Perhaps if JavaScript supported multiple inputs (or destructuring of arrays) in a switch..case I could see something like this:
switch (numRegex.test(phoneVal), alphaRegex.test(usernameVal)) {
case false, false:
console.log('Neither are valid.');
break;
case true, false:
console.log('Invalid username.');
break;
/* snip */
default:
console.log('All\'s good.');
}
But alas, I'd say sticking with if..else is a better and easier to follow/understand option, in this case:
if (numRegex.test(phoneVal)) {
console.log('Only digits please.');
return false;
} else if (alphaRegex.test(usernameVal)) {
console.log('Only alpha-numeric please.');
return false;
} else {
console.log('It\'s all good.');
return true;
}
If you are only using each regex once why not just refactor this into a block of ternaries?
Maybe something like this:
/^\S/.test($('#name').val()) !== true
? invalidEls.push('name:invalid')
: invalidEls.push('name:valid');
$('#phone').val().match(/^(1-?)?([2-9]\d{2}|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)
? invalidEls.push('phone:valid')
: invalidEls.push('phone:invalid');
$('#email').val().match(/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9]){1,}?/)
? invalidEls.push('email:valid')
: invalidEls.push('email:invalid');
Another similar pattern;
try {
if (!alphaRegex.test(usernameVal))
throw ('Only letters please.');
if (!numRegex.test(phoneVal))
throw ('Only digits please.');
...
return true;
} catch (e) {
console.log(e);
}

Categories

Resources