Javascript RegEx.Test always returning true - javascript

I have a value in a text input I need to verify as a date in the format dd/mm/yyyy. Below is my code. I always get true regardless of what I enter in the text input. Otherwise function works well. Always displays an alert with the value I put in the text input.
function checkDate(date)
{
var result;
var expression = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
result = expression.test(date.value);
if(result=true)
{
alert(date.value);
}
else
{
alert("false finally");
}
}

if(result==true)
{
alert(date.value);
}
instead having single "=" have "==" , else you can use like this
if (result)
{
alert(date.value);
}
and always remember this
"1" == 1 // true
"1" === 1 // false
An example of type coercion at work. Basically anytime your value is the "same" but the type isn't then == works.
Please use === everywhere. There's no need to use ==. checking for types is always better. If something breaks then you can convert from type a to type b

Related

How come the if-statement is skipped when I am checking if a string is equal to a number?

I am trying to see if the user input is equal to a number, and if it isn't, then show a label saying, "Must be a number" and do not proceed until it is. I never learned about how to check if a string is equal to a number, so I searched it up and added it to my code, but it still doesn't work. Can someone look at it and tell me how I can fix my if-condition? Thank you in advance!
//variable that is used
var user_answer = getNumber("answer_input");
//Confirm your answer with clicking the button
onEvent("attackBttnForEquation", "click", function( ) {
if (isNaN("user_answer") === false){ //here is where I tried to use it, but it just skips the condition
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
setScreen("play_screen");
hideElement("fight_symbol");
checkAnswer();
checkLose();
});
This is what I tried based on a comment and it still did not work:
onEvent("attackBttnForEquation", "click", function( ) {
if (isNaN(user_answer) === true){ //I forgot to specify that user_answer is a variable, but I even set the condition to equal to true and it did the same thing as before.
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
Okay, with the answer I got, the "mustBeNum_label" shows, BUT when the user inputs an actual number, it still shows "mustBeNum_label".
//Confirm your answer with clicking the button
onEvent("attackBttnForEquation", "click", function( ) {
if (Number(user_answer)){
setScreen("play_screen");
hideElement("fight_symbol");
checkAnswer();
checkLose();
} else {
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
});
Try checking like this:
if (Number(user_answer) || user_answer == 0) {
// input is a number
} else {
// input is not a number
}
You can find out more here: Number - MDN
I would consider this a poor case for Number() since it will output NaN or a number.
Consider when you encounter 0: the conditional will run your else block since 0 is falsey.
Number.isInteger(Number(user_input)) may be a better solution since it will always output a boolean, and if it gets passed NaN will output false.
Shorter syntax would be Number.isInteger(+user_input)

How do I check if a variable is null, so that I can change it later on?

A group of me and two other people are working to make a Jeopardy game (themed around United States History questions) all in JavaScript. For our final Jeopardy screen, the two teams will each bet a certain amount of money. To prevent a team from typing in random letters for a bet (i.e typing in "hasdfhgasf" instead of an actual amount), we're trying to write an 'onEvent' command that checks to see if a bet is null. If that bet is null, then the code should come up with a message on the screen that tells them to check their bets again.
We tried using statements like, if "null" or if " " but neither of these statements works. We've worked with using getNumber and getText commands, along with just regular variable comparisons with or booleans. So far, we haven't had any luck with these methods.
Here's the group of code we're having issues with:
onEvent("finalJeopardyBetSubmit", "click", function() {
team1Bet = getNumber("team1BetInput");
team2Bet = getNumber("team2BetInput");
console.log(team1Bet);
console.log(team2Bet);
if (getText("team1BetInput") == "" || getText("team2BetInput") == "") {
console.log("Check bet!");
finalJeopardyError();
} else if ((getText("team1BetInput") != 0 || getText("team2BetInput") != 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") < 0 || getNumber("team2BetInput") < 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") > team1Money || getNumber("team2BetInput") > team2Money)) {
console.log("Check bet!");
finalJeopardyError();
} else {
console.log("Done");
}
});
You can also check out the whole program on Code.org if you'd like to get a better look.
We expect that with the console.log commands, it should say "check bet" if the bets return as null. Instead, the code has ended up fine, and not displaying our error message, even if we type in nothing or just random letters.
a null variable will evaluate to false. Try:
if(variable){
// variable not null
}else{
// variable null
}
Convert the value to a Number first using Number(value) and then check for falsy values using the logical not ! operator. If they enter alphabetic characters, then calling Number('abc') results in NaN.
If a value can be converted to true, the value is so-called truthy. If
a value can be converted to false, the value is so-called falsy.
Examples of expressions that can be converted to false are:
null; NaN; 0; empty string ("" or '' or ``); undefined.
The ! will change any of the falsy values above to true, so you can check for all of them with just the first if statement below.
onEvent("finalJeopardyBetSubmit", "click", function() {
// Convert these values to numbers first
var team1Bet = Number(getNumber("team1BetInput"));
var team2Bet = Number(getNumber("team2BetInput"));
if (!team1Bet || !team2Bet) {
// Handle invalid number error
}
else if (team1Bet < 0 || team2Bet < 0) {
// Handle invalid range error
}
else if (team1Bet > team1Money || team2Bet > team2Money) {
// Handle insufficient funds error
}
else {
// Finish game
}
})
You can read more about the logical operators here.

How do you get a if statement between an Element and Infinity?

I want to be able to have an if statment saying that if an element is equal to Infinity, it gives out a different phrase than "Infinity"(my element is an input box) here is my if statement:
if (document.getElementById("box").value === Infinity) {
document.getElementById("box").value = "STOP PRESSING BUTTONS"
}
I'm still very new to javascript/html so I might've gotten some of the terms wrong.
Try this...
if (result == Number.POSITIVE_INFINITY || result == Number.NEGATIVE_INFINITY)
{
// ANY LOGIC
}
You could possibly use the isFinite function instead, depending on how you want to treat NaN isFinite returns false if your number is POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN.
if (isFinite(result))
{
// ANY LOGIC
}

javascript isNaN() function not working?

I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.

Am I using the isNAN function in JavasScript correctly here?

I've got a form where the user inputs 3 values, which are then calculated. The outputs are displayed again within the form in some "readonly" output boxes. For each input, I want to validate if they are a number, if not, instead of the form showing "NaN" I want to display an error saying, "Please enter a number" (or something like that). Below is the code I am using, which is executed "onkeyup":
function checkforNumber()
{
if (isNaN(sInput || dInput || pInput) == true) {
alert("You entered an invalid character. Please reset the form.");
}
else {
return(false);
}
}
Am I using this function incorrectly? Is there something wrong with the syntax?
Thanks
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please reset the form.");
}
also make sure that those 3 variables sInput, dInput and pInput are not strings but were obtained by using parseFloat or parseInt methods.
var sInput = parseFloat(document.getElementById('sinput').value);
var dInput = parseFloat(document.getElementById('dinput').value);
var pInput = parseFloat(document.getElementById('pinput').value);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput))
This is what I think you intended. You need to pass each value you want to test in to the isNaN function one at a time. Also note that you don't need the == true part, because isNaN returns true or false so the condition will evaluate to the return value.

Categories