Input number with min and max

Have created input number and tried to make a validation with JavaScript so the minimum of number that can be written is 1 and maximum would be 50 but cannot figure it what’s wrong because it doesn’t show any error in Console?

    document.getElementById('info1').addEventListener("input", function () {
    let num = +this.value, max = 50, min = 1;
    if (!this.value.length || this.value.max > 50 || this.value.min < 1) 
    return false;
        <span class="info-1">Type something</span>
        <input type="number" id="info1" size="4">

Why are you not comparing num to something?

If you mean about num.value.length num.value.max num.value.min I didn’t compare them because with this I thought it will refer to function and would compare them.

this is the input element.

Yeah this is the input function, but about num should I replace this in if statement or add another if statement with num?

No, this is the input element. You declare a variable named num and assign it the value of +this.value which is the value of the input entered by the user. You should be comparing num to max and min which are the other variables you have initialized.

Also, what are you expecting your function to do if the value entered is less than 1 or great than 50? Currently, you are returning the value false if that is the case.

About function when the value is less than 1 and greater than 50 it would return false and it would replace immediately any number less than 1 (0,-0,-1, etc ) with number 1 or number greater than 50 (51,52,53, etc) with number 50.

First thing that I noticed is that you have an input of type number and you are using this.value.length to make a comparison, you might want to double check what type='number' is because it may be doing something different to what you think it does.

If you don’t care about the length of the string but the actual value passed in the input, then you only need this.value, the length property wouldn’t be necessary. For example if the user passes 0 to the input you probably wanna throw an error or logging in the console, even though 0 would have a length of 1, but 0 (actual value) would be less than 1.

Considering that the above is what you are trying to achieve, this can easily be done with an if statement. If the user passed in a value less than 1 or greater than 50, return whatever you wanna return, say a console.log('error here')

Also, what do you think this is doing this.input.value.max?

I am not going to give you the entire solution you seek, but since you already have declared 3 variables (num, min, and max) I will show you how you would return the value false based on if the value is less than 1 and greater than 50. It would take some extra logic to force the value to be 1 for values entered less than 1 or 50 for values entered greater than one.

  if (num > max || num < min) {
    return false;
1 Like