greater than function does not work when 0 is inputted - javascript

I need to validate the user input where user can only enter the value not equal to but greater than 0 and smaller than stated value. My validation logic works if i provide certain object
{required:true, greaterThan: 1, smallerThan: 50}
Here, if i input the value 0, then it displays an error message saying, value should be greater than 1 but if in case, i provide the following object instead
{required:true, greaterThan: 0, smallerThan: 50}
and I input the value 0 then it does not display an error message saying value should be greater than 0
Here is my validation logic
if (fieldValue.smallerThan && value && parseInt(value, 10) > fieldValue.smallerThan) {
set(
errors,
key,
`${fieldValue.label} should be smaller than ${fieldValue.smallerThan}`,
)
}
if (fieldValue.greaterThan && value && parseInt(value, 10) < fieldValue.greaterThan) {
set(
errors,
key,
`${fieldValue.label} should be greator than ${fieldValue.greaterThan}`,
)
}

0 && any value
Will always result in false because 0 is considered as falsy value in javaScript
What You can do is
fieldValue.greaterThan >= 0 && ..

If you're just checking for existence of the greater than property in the fieldValue, which seems to be what you're doing, you might also considering editing your two checks to be:
if (fieldValue.smallerThan !== undefined && ...)
and
if (fieldValue.greaterThan !== undefined && ...)
In general, relying on the truthiness or falsiness of values gets you into trouble, and it's better to be explicit about what you are checking for.

always convert your inputs to an integer or float.
if(!(fieldValue.smallerThan < parseInt(value))){
...value must be smaller than 50
}
if(!(fieldValue.greaterThan > parseInt(value))){
...value must be greater than 0
}

Related

Check when a value is equal to 0

I have a process that runs when the command is issued in the discord bot, sometimes this process will fail and I need to know when it does. Every time after the command is issued and the process finishes it logs in console
console.log ('Process done! All succeded: %s || All failed: %s'), allsucces, allfailed
So every time all succeded = 0 I want the bot to dm me in a discord message
You can simply compare allsucces value to 0
if (allsucces === 0) {
/* DM Logic */
}
These links might also provide you with some useful information regarding Javascript and how Comparison and logical Operators work:
Javascript Basics
JavaScript Comparison and Logical Operators
To compare 2 values, use comparison operators.
Here's how they work:
val == 0 // val has the value 0 but does not *need* to be the same type ("0" == 0 is true)
val === 0 // val is 0, both in value and type
val != 0 // opposite of "==" - val does not have the value 0
val !== 0 // opposite of "===" - val does not have the value 0, or is not the same type
val > 0 // val is more than 0
val < 0 // val is less than 0
val >= 0 // val is more than or equal to 0
val <= 0 // val is less than or equal to 0
See the difference between === and == in this question
To implement this in your code, use the === operator
if (allsucces === 0) {
// allsucces is equal to 0
}
And be sure allsucces is a number, not a string, otherwise the strict equals operator will make it return false!

javascript how to set null input equal to 0

I have javascript function that will calculate the value for "TOTAL" row and "Balance" column in the table. But if there are no input, the javascript will return NaN which is not a number error.
How to set if there are no input in the text box, javascript will interpret it as 0 so that I will not get NaN error.
As you can see, the textbox for pay(notes 50) column are empty. Then value for balance and total become NaN.
just use logical 'or' operator (see short-circuit evaluation),
parseInt('10') || 0; // give 10
parseInt('') || 0; // give 0
You can check whether the value is a number by isNaN() function and then perform summation.
use isNaN(), put it in an if statement, if true, set the variable to 0
if(isNaN(yourVar)) {
yourVar = 0;
}
Ternary operator will work just fine
yourVar = (isNaN(yourVar)) ? 0 : yourVar
So if you want to check if your textbox value is empty or not, you can use:
val = your_textbox_value == '' ? 0 : your_textbox_value
assign that object to it this will work fine
you_object = you_object == null ? "0" : you_object;

Check for numeric value or range

A input-field could have values like:
23
23-45
No I want to correct the value:
string.replace(/[^\d-]/g,'');
But that doesn't correct these values:
-45
23-
45-23
10-110
All these values are incorrect (The valid values are from 0-100 (as they are percentage values), so 110 is unvalid). So for that cases I want the user to have a second look at the input field...
I guess I have to create a second RegEx for these unvalid cases, right?
function to return true if a percentage is represented by whole numbers, where if a dash is included the first number is less than the second, and both numbers are between 0 and 100:
function isValidPercentage(input) {
var mat = /^(\d+)(?:-(\d+))?$/.exec(input + "");
if (mat !== null && ((mat[2] === undefined && mat[1] < 101) || (mat[1] < mat[2] && mat[2] < 101))) {
return true;
}
return false;
}
Edit#1: To force the false return if either number is greater than 100
Edit#2: Fixed errors, cleaned up the code a bit
Say you have an input (#perc) and a button (#calc), then try:
document.querySelector('#calc').addEventListener('click', calculate);
function calculate() {
// replace all non numeric values in the input with nothing
// and convert it to a Number (using the + operator).
var value = +(document.querySelector('#perc').value.replace(/[^\d]/g, ''));
// now you can check the value
alert( !isNaN(value) && value >= 0 && value <= 100
? 'ok ' + value
: 'not ok ' + value );
}
The SO-inline code inserter is not working, so you'll have to try it out yourself.

javascript testing .length and .length > 0

I have some text in an object's property. I'm testing to see if the object's property has text in it to display; if it doesn't then I display "-" instead of just a blank. It doesn't seem like there's a difference between:
if (MyObject.SomeText && MyObject.SomeText.length) { ... }
if (MyObject.SomeText && MyObject.SomeText.length > 0) { ... }
Are there any edge cases where one syntax would be preferable to the other?
Are there any edge cases where one syntax would be preferable to the other?
Only edge cases where MyObject.SomeText or MyObject.SomeText.length is not what you expect it to be – for instance:
MyObject = {
SomeText = {
length: -42
// or length: true
}
};
they give same result. Btw, if its "text", then if (MyObject.SomeText) is enough
No, they are equivalent, if the length equals to 0 then it is valued as false.
(This is possible because JS is not strongly typed, in strongly typed languages length would not be castable as boolean).
In javascript, a number is only considered "falsey" when it is 0. Any other value is "truthy". Therefore, the statements number != 0 (comparison, not identity) and !number are exactly equivalent.
The only way your two statements would differ is if length was something other than a positive number.
It's the same:
Boolean(MyObject.SomeText.length)
returns true if MyObject.SomeText.length != 0
returns false if MyObject.SomeText.length == 0
and
Boolean(MyObject.SomeText.length>0)
returns true if MyObject.SomeText.length > 0
returns false if MyObject.SomeText.length <= 0
But MyObject.SomeText.length can only be 0 or a positive integrer. So
If MyObject.SomeText.length == 0,
Boolean(MyObject.SomeText.length) returns false because MyObject.SomeText.length == 0
Boolean(MyObject.SomeText.length>0) returns false because MyObject.SomeText.length<=0
If MyObject.SomeText.length > 0,
Boolean(MyObject.SomeText.length) returns true because MyObject.SomeText.length != 0
Boolean(MyObject.SomeText.length>0) returns true because MyObject.SomeText.length > 0

Difference between Boolan(!x) and Boolean(x==0)?

Code-snippet 1:
if ( !x ) { /* do stuff */ }
Code-snippet 2:
if ( x == 0 ) { /* do stuff */ }
For what values of x do these two code-snippets differ?
I am asking because, although I read the chapter on == in the spec, I still find it hard to deal with situations like the above (where it is combined with ToBoolean coercion).
btw, I want to know this just for the sake of knowing it (I want to understand the language), so don't bother telling me about === or asking me what x is.
Update: I corrected the fist snippet. I meant !x.
[] == 0 is true; ![] is false
null == 0 is false; !null is true
NaN == 0 is false; !NaN is true
undefined == 0 is false; !undefined is true
!x will check whether x is "falsy".
x == 0 will check whether x is "equivalent to" 0.
Both of these terms are defined by the Javascript spec.
The following will give you true for the first and false for the second snippet:
NaN
null
undefined
And these will give you false for the first and true for the second snippet:
[]
"0" and any other string that converts to 0 using Number(x) such as "00", "000", "+0", and "-0" (which I will now call "noughty strings")
an array containing a single element that is 0, null, undefined or an empty or noughty string.
For everything else you'll get the same result for both snippets, although there may be one or two more cases I haven't thought of.
Here's an interesting one with regard to a non-empty String that has only space characters:
!!" "; // true
" " == true; // false
This is because when you do a == comparison, and one of the values being compared is a number or a boolean, an attempt is made to convert the other value to a number.
The reason you get the different result is that a string with only space characters converts to the number 0 (or falsey), while a string with only spaces converted to boolean via !! is seen as a non-empty string, and therefore true.
So:
var x = " ";
alert( !x ); // false
alert( x == 0 ); // true
EDIT:
Probably the key thing to remember is that when comparing a number or boolean to a non number type, == uses toNumber conversion if possible, while ! uses toBoolean conversion. They're not always the same.
It is easy to see the result of the toBoolean conversion using !!. As in:
alert( !![] ); // true
But you can't really see the result of the toNumber conversion when using ==.
You can, however, use the unary + to see the result of a toNumber conversion. As in:
alert( +[] ); // 0
I'm pretty sure that what happens in the case of an Array, is that it first gets a toString call. Therefore:
// ---------------------toString result-------toNumber result (from string)
alert( +[] ); // "" 0
alert( +[""] ); // "" 0
alert( +[" "] ); // " " 0
alert( +[0] ); // "0" 0
alert( +["0"] ); // "0" 0
alert( +["3"] ); // "3" 3
alert( +[3,4] ); // "3,4" NaN
Short answer: the two are almost always the same but not 100% the same.
An example would be (!'0') which is false whereas ('0' == 0) is true
Details:
From: http://www.joeyjavas.com/2007/08/04/javascript-true-false-checking-for-boolean-values/
Checking if a value is true or false is simple in JavaScript. All values evaluate to true, except for:
0
-0
null
undefined
NaN
empty string
false
Therefore, (!x) will be true for all of the above values of x and only those.
As for (x == 0), it will be true for any value of x which - when converted according to "==" conversion rules - is converted to 0 when compared to a number (for example, Boolean false value). Other examples that compare true to ==0 are objects which generate 0 from their valueOf() methods, or a string '0', or an empty Array ([])
The first test will succeed when x is non-zero, or evaluates to an object (as opposed to null or undefined), or is a non-empty string. So if x is 0 then the condition fails, but if it is "0" then it succeeds.
The second test will succeed when x is convertible to 0. This means it must not be null, undefined, or an object to pass this test. And it may be "0" or "".
In other words, these conditionals are not opposites. The value "0" will pass both tests, for example.
Code Snippet 1 will execute if x is "falsy" value. In Javascript, this means 0, -0, null, undefined, NaN, "", or false. Code Snippet 2, however, will only execute if x is zero. Unlike the first condition, this does not include other "falsy" values.
The difference between the two is that
if ( x ) { ... }
Tests whether x is "truthy"
Whereas
if ( x == 0 ) { ... }
Does type coercion between x and 0.
I presume you mean something like
if (x == 0) vs if (!x)
The main difference is type coercion of x to a number vs checking if x is falsy.
Clearly NaN itself will never equal 0 since its not a number. undefined will also coerce to NaN so that is not caught by == 0 I can't give a good explanation why null is not caught by 0 since Number(null) == 0
After some lookups, have to change my awnser.
There's no simple logic, implicit equality operations follows an algorithm.
http://interglacial.com/javascript_spec/a-11.html#a-11.9.3
I can't sum it up better then what the algoritm describes, it would just get more confusing.
So it's (!x) is equivalent to (typeof x === false) aka (not true)
And (x == 0) gets compared by algorithm.

Categories