befb
befb

Reputation: 21

Adding a validation for input type, so the user is not allowed to enter anything other than numbers with a min and max value

I'm trying to do this in HTML for now where I have a input field of type=number where I don't want the user to be able to type decimal values/special characters/alphabets at all. I also want the min=30 and max=300so if a user types 29 and clicks else where, the value in the field should change to the min which is 30. If the user types in a value greater than 300 and clicks elsewhere, then I want the value to change to 300 which is the max. I don't want to wait for the user to wait for them to click on a form button. This is what I have so far, where the error is that, the user can still type decimal, and type any value lower than 30. Very new to html/js. Feel free to help me with js implementation if you think that is easier.

<input type="number" min="30" max="300" step="1" oninput="validity.valid||(value=value.replace(/\D+/g, ''))" id="seconds" name="seconds" value="30">

Upvotes: 0

Views: 981

Answers (1)

Akash Sinha
Akash Sinha

Reputation: 309

<html>

<script>

    function change(){

        var inp  = document.getElementById("box").value;
        
            inp = Math.floor(inp);  
            if(inp<30){

            document.getElementById("box").value = 30;

        }

            else if(inp>300){

            document.getElementById("box").value = 300;

        }
        else {
            document.getElementById("box").value = inp;
        }
    }

                

</script>

<BODY>

<input type= "number" onmouseout = "change()" id ="box"/>

</BODY>

</HTML>

this java script should do use "onmouseout".

Upvotes: 3

Related Questions