anakin
anakin

Reputation: 3

How to pattern html5 input

I have input like this

<input max="100" min="0" type="number">

But in this input users can put numbers like 01 02 03 004 itp... And my question is how to prevent this? To only numbers from 0 to 100

0, 1, 2, 3 ... 100

Upvotes: 0

Views: 36

Answers (2)

Victor
Victor

Reputation: 437

In most cases JavaScript is the answer:

<input type="text" id="taskinput">
<script>
    const input = document.getElementById('taskinput');

    let lastValue = '';

    input.oninput = () => {
        if (!input.value) {
            lastValue = '';
            return;
        }

        const val = parseInt(input.value);

        if (val > 100 || isNaN(val)) {
            input.value = lastValue;
            return;
        }

        lastValue = val;
        input.value = lastValue;
    }
</script>

Upvotes: 1

Dontwan
Dontwan

Reputation: 121

You could archive this by adding a onchange eventlistener on the input.

The regex will remove the leading zero.

document.getElementById('number').onchange = function(){
	this.value = this.value.replace(/\b0+[0-9]/g, '');
};
<input id="number" min="0" max="100" step="1" type="number" >

Upvotes: 0

Related Questions