简体   繁体   中英

greater than function does not work when 0 is inputted

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM