I made a simple little calculator for math class. It does simple things like find volumes and areas of certain shapes, but saves me a lot of time in homework.
I uploaded it to the internet for my classmates, but I figured I would make the forms only be able to have numbers in them. I found some answers on tizag, but I don't really understand those solutions.
I'm looking for something like this:
function calculation() {
if (form.thenumbers.value = code to check if it is numeric)
{
calculations
} else {
alert("Numbers only please");
}
}
If it can't be that simple, I just appreciate a little explanation to how any other way works. Thanks.
if (form.thenumbers.value.match(/^[\d]*$/)){
//do stuff
}
Should work for you. This will match the value for a 0 or more digits. If you would like it to match for 1 or more, use + in place of *.
Related
I have an idea for a game where people can type in some simple instructions for their character like player.goLeft() or player.attackInFront() and for that I have people type their code into a text box and then I parse it into eval(). This works well but it also allows people to change their own character object by typing things like player.health = Infinity; or something similar. I have a list of functions I want to allow people to use, but I am unsure how to restrict it to only use them.
I understand that the whole point of not letting people use eval is to avoid accidental cross-site scripting but I am unsure on how else to do this. If you have a suggestion please leave a comment about that.
I asked some people around on what to do and most suggested somehow changing scope(which is something I was not able to figure out) or to add some odd parameter to each function in my code that would be required to be a specific string to execute any function, but that seems hacky and since I am making the game in browser with p5js it would be easy to just inspect element and see what the password is.
basically every character has variable called "instruction" which is just a string of javascript. Then every frame of the game I execute it by doing eval(playerList[i].instruction);
tl;dr, how can I only allow specific function to be executed and not allow any others?
EDIT: I forgot to mention that I also am planning to provide player with information so that people can made code that would adapt to the situation. For example there will be parameter called vision that has vision.front and vision.left etc. These variables would just say if there is an enemy, wall, flower, etc around them in a grid. Some people suggested that I just replace some functions with key words but then it compromises the idea of using if statements and making it act differently.
EDIT 2: Sorry for lack of code in this post, but because of the way I am making it, half of the logic is written on server side and half of it works on client side. It will be a little large and to be completely honest I am not sure how readable my code is, still so far I am getting great help and I am very thankful for it. Thank you to everybody who is answering
Do NOT use eval() to execute arbitrary user input as code! There's no way to allow your code to run a function but prevent eval() from doing the same.
Instead, what you should do is make a map of commands the player can use, mapping them to functions. That way, you run the function based on the map lookup, but if it's not in the map, it can't be run. You can even allow arguments by splitting the string at spaces and spreading the array over the function parameters. Something like this:
const instructions = {
goLeft: player.goLeft.bind(player),
goRight: player.goRight.bind(player),
attackInFront: player.attackInFront.bind(player)
};
function processInstruction(instruction_string) {
const pieces = instruction_string.split(' ');
const command = pieces[0];
const args = pieces.slice(1);
if (instructions[command]) {
instructions[command](...args);
} else {
// Notify the user their command is not recognized.
}
};
With that, the player can enter things like goLeft 5 6 and it will call player.goLeft(5,6), but if they try to enter otherFunction 20 40 it will just say it's unrecognized, since otherFunction isn't in the map.
This issue sounds similar to the SQL Injection problem. I suggest you use a similar solution. Create an abstraction layer between the users input and your execution, similar to using parameters with stored procedures.
Let the users type keywords such as 'ATTACK FRONT', then pass that input to a function which parses the string, looks for keywords, then passes back 'player.attackInFront()' to be evaluated.
With this approach you simplify the syntax for the users, and limit the possible actions to those you allow.
I hope this isn't too vague. Good luck!
From your edit, it sounds like you're looking for an object-oriented approach to players. I'm not sure of your existing implementation needs, but it would look like this.
function Player() {
this.vision = {
left: '',
// and so on
}
}
Player.prototype.updateVisibilities = function() {
// to modify the values of this.visibility for each player
}
Player.prototype.moveLeft = function() {
}
Don't give the user an arbitrary interface (such as an input textfield that uses eval) to modify their attributes. Make a UI layer to control this logic. Things like buttons, inputs which explicitly run functions/methods that operate on the player. It shouldn't be up to the player as to what attributes they should have.
Found some things like in Visual Basic but not Javascript and exactly what I'm trying to do. It's a tad bit different. I'm trying to figured out how to rearrange characters in a string, it's in a for loop as well in order to cut the string in half. Now I need to rearrange that.
First I have:
12345678910111213141516
then in the for loop
12345678
I'm trying fix it so now I get
72648531
But I have to do it in a way so people can't read the code and know that there's 8 characters at this point in the string without hard work and trouble. My for loop is also jumbled up and screwy so it can't be figured out. Something like this. I really cannot post the code though.
var con = "";
for (var i = complex math that equals 0; i < complex math to equal 8; i++) {
var newStr = word[i]; // I need it to come out to the rearranged somewhere close by
var con = con+""+newStr;
}
Two commonly used techniques come to mind:
A common approach to things is by doing some XOR calculations: Look at this unrelated examples:
http://www.javascriptsource.com/passwords/xor-encryption4.html
Extracting information from page with Jsoup
You can use tools like http://www.javascriptobfuscator.com/Default.aspx to make it harder for people to figure your code.
What I'm trying to do is prompt the user repeatedly until one of the accepted answers is received. Pretty easy stuff. The while loop, however, is making this really weird and annoying. Here's what I got:
var plrchoice=prompt("Would you like to choose Bulbasaur, Charmander, or Squirtle? (Use only lowercase characters)");
while(plrchoice!=="bulbasaur"||plrchoice!=="charmander"||plrchoice!=="squirtle"){
plrchoice=prompt("Would you like to choose Bulbasaur, Charmander, or Squirtle?");
}
This should work in theory, but the result is an infinite do/while, regardless of what the user inputs. Thanks in advance :)
Those || should be &&.
If your rewrite the code like this, it may be clearer what happens:
var plrchoice = "";
while (!/^(bulbasaur|charmander|squirtle)$/i.test(plrchoice)) {
plrchoice =
prompt("Would you like to choose Bulbasaur, Charmander, or Squirtle?");
}
At the moment I'm learning jQuery and I hit the topic about if/else statements. As I have no background in programming this topic is something that I need to practice a bit more to get a thorough understanding of it.
The book I'm studying gave me the advice of just writing different blocks of if/else statements. I just had an idea and wanted to know if its valid:
$(morningWakeup).ready(function() {
$('#arms').reaction(function() {
if($'#kid').is(':nagging')) {
$('#kid').slap();
} else {
$('#kid').hug();
}
});
});
Let me make it clear that this is a joke of course, but I want to know if this is valid code and if you can supply me with some more examples? Thank you!
The basic form is perfectly fine, though you've misplaced some parentheses on this line: if($'#kid').is(':nagging')) {. It should be if ($('#kid').is(':nagging')) { instead. Also, note that you'll have better luck setting $('#kid').attr('behaving') to true if you just ignore() him/her for a while instead of slap()ing them. Negative reinforcement sucks. :)
You're mixing up Javascript and jQuery here: The if/else is basically valid, but the jQuery part (.is etc.) will strongly depend on whether the DOM elements exist, whether they have that property etc.
I would recommend starting with real live HTML to go along.
That, and of course the syntax error #bcat points out...
I am writing a simple syntax highlighter in JavaScript, and I need to find a way to test with multiple regular expressions at the same time.
The idea is to find out which comes first, so I can determine the new set of expressions to look for.
The expressions could be something like:
/<%#/, /<%--/, /<!--/ and /<[a-z:-]/
First I tried a strategy where I combined the expressions in groups like:
/(<%#)|(<%--)|(<!--)|(<[a-z:-])/
That way I could find out which matched group was not undefined. But the problem is, when some of the subexpressions contain groups or backrefferences.
So my question is this:
Does anyone know a good and reasonable way the look for matches with multiple regular expressions in a string?
Is there any particular reason why you can't tokenize the input and then test the beginning of each token to see what type it is for the purposes of highlighting? I think you're overthinking this one. A simple cascade of if-elseifs will cover this just fine:
if (token.startsWith("<%#")) {
// paint it red
}
else if (token.startsWith("<%--")) {
// paint it green
}
else if (token.startsWith("<!--")) {
// paint it blue
}
else if (token.matches("^<[a-z:-]")) {
// paint it black
}
The above is pseudocode and needs to be magically translated into JavaScript. I leave this as an exercise for the reader.
ANTLR is an excellent grammar development system. There's a project to build a JavaScript back-end for it at http://code.google.com/p/antlr-javascript/
I agree with Welbog's answer to your regex question, but you can probably learn a lot about implementing JavaScript grammars by looking at the ANTLR generated ones.