简体   繁体   中英

Min Max validation with javascript

I have the following input:

<input type="number" class="form-control custom-values" name="Width" id="item-b" min="1201" max="1500" value="1361">

I'm trying to make sure that the value input by the user is within the min max boundaries. However, I'm running into an odd issue.

When I use this script to check the values:

if($(this).val() > $(this).attr("max") || $(this).val() < $(this).attr("min")){
        alert("out of bounds");
        all_custom_sizes_valid = false;
    }else if($(this).val() < $(this).attr("max") || $(this).val() > $(this).attr("min")){
        if(!all_custom_sizes_valid){
            alert("fixed to in bounds");
            all_custom_sizes_valid = true;
        }else{
            alert("in bounds");
        }
    }

Things generally work fine.

However, when I input 150 into the input box, it gives me an alert that the value is within bounds. 150 is the only number I've been able to find that does this.

I've also had other issues with the validation not updating properly when I change back to a valid value and the "Fixed to in bounds" alert not popping up.

Any insight would be greatly appreciated.

You are comparing strings. Both $(this).val() and $(this).attr("max") are string (as is the value of the min attribute).

Looking at the tests this way, both of these are true: "150" > "1201" and "150" < "1500" (you can try in the browser console). You can use parseInt() to get integer values that you can compare.

Another problem is you should have && instead of || between comparisons (you want it to be greater than min and also smaller than max).

Also it would look nicer (to me at least :) ) if you got the values into variables first, there you could apply the int conversion too: var currentValue = parseInt($(this).val()) , etc.

Right now all your comparisons are strings, not numbers. Try using parseInt or similar operations to convert each value to a number before comparison

Your else if statement shouldn't be using || .

It should be

else if($(this).val() < $(this).attr("max") && $(this).val() > $(this).attr("min")){

I think the reason why 150 passes is because of this line

if($(this).val() < $(this).attr("max") || $(this).val() > $(this).attr("min")){

It leaks through because of the OR operator. 'If 150 is < 1500 Or 150 > 1200' then do stuff...

Javascript sees that the first condition is satisfied and thus proceed to enter the if loop. Replace with an AND '&&' operator.

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