Prevent negative inputs in form input type=“number”?

前端 未结 8 956
太阳男子
太阳男子 2020-12-12 16:58

I want to restrict user input to positive numbers in an html form.

I know you can set min=\"0\", however it is possible to bypass this by manually entering a negati

8条回答
  •  盖世英雄少女心
    2020-12-12 17:47

    This is not possible without validating the value of the input.

    input type=number

    The input element with a type attribute whose value is "number" represents a precise control for setting the element’s value to a string representing a number.

    Since it is a string representing the number there is no way to be sure that string may be representing numeric values or not.

    The Permitted attributes will not give you the ability to validate the value of the number input control.

    One way to do this with the help of JavaScript could look like this.

    // Select your input element.
    var numInput = document.querySelector('input');
    
    // Listen for input event on numInput.
    numInput.addEventListener('input', function(){
        // Let's match only digits.
        var num = this.value.match(/^\d+$/);
        if (num === null) {
            // If we have no match, value will be empty.
            this.value = "";
        }
    }, false)

    If you are planing on sending your data to a server make sure to validate the data on the server as well. Client side JavaScript can not ensure that the data that is being sent will be what you expect it to be.

提交回复
热议问题