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);
}
Related
if (valid === null) {
return '';
} else if (!valid) {
return 'is-not-valid';
} else if (valid) {
return 'is-valid';
} else {
return '';
}
I have the above if-else-if chain in the code, trying to see if I can write the same logic in one or two lines.
Since you want to distinguish between three types of values, you have to make at least two checks already. The else case will never be hit since either !valid or valid will be true. That also means you can reduce the last else if to an else:
if (valid === null) {
return '';
} else if (!valid) {
return 'is-not-valid';
} else {
return 'is-valid';
}
But you could condense this logic using the conditional operator:
return valid === null ? '' : (valid ? 'is-valid' : 'is-not-valid');
Although I think your example (sans the redundant else block) looks pretty good, you can write it on one line like this:
return valid === null ? '' : (valid ? 'is-valid' : 'is-not-valid')
I prefer the original though
I would like to transfer my if condition to switch case, because then it would look nicer in my code. (I have several switch case).
I can't set the switch parameter to true, because this will break the logic of my code.
if (/(.*)_ERROR/.test(action.type)) {
alert('ok'); //working
}
switch (action.type) {
case /(.*)_ERROR/:
alert('ok'); //not working
break;
...
}
How to write it? The idea is to enter the case only if the word "error" is in the string
Not very ideal but you can use named groups:
const reg = /(?<warning>(.*)_WARNING)|(?<error>(.*)_ERROR)|(?<info>(.*)_INFO)/; // warning, error, or info.
const match = action.type.match(reg);
if (match) {
const groupName = Object.keys(match.groups).find(group => match.groups[group] !== null);
switch (groupName) {
case 'error': // like TEST_ERROR
case 'warning': // like TEST_WARNING
case 'info': // like TEST_INFO
default:
}
}
I have this simple javascript function:
function updateDeleteUser(action, userid) {
frm = document.getElementById("frmsearch");
frm.frmUserId.value = userid;
switch (action) {
case 0:
frm.action = "UpdateUser.jsp";
break;
case 1:
confirm("Delete account?");
if (confirm != false){
frm.action = "DeleteUser.jsp";
}
}
frm.submit();
}
Even if I click on 'NO' the function runs anyway and user gets deleted. What did I do wrong?
Thanks in advance.
You are not doing anything with the return value of the confirm(…) call, instead you use the confirm function itself as the compare value in your if-condition. You want
if (confirm("Delete account?")) {
frm.action = "DeleteUser.jsp";
}
Notice that this has nothing to do with the switch statement.
You are using Confirm Method is wrong position as it always behaves like native function.#
Correct usage is as follows
case 1:
// confirm("Delete account?");
if (confirm("Delete account?") != false){
frm.action = "DeleteUser.jsp";
}
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);
}
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.