How to make type=“number” to positive numbers only

后端 未结 17 2436
既然无缘
既然无缘 2020-11-30 17:12

currently I have the following code


it comes out to something like this

17条回答
  •  不知归路
    2020-11-30 17:52

    It depends on whether you want an int or float field. Here's what the two would look like:

    
    
    

    The int field has the correct validation attached to it, since its min is 1. The float field accepts 0, however; to deal with this, you can add one more constraint validator:

    function checkIsPositive(e) {
      const value = parseFloat(e.target.value);
      if (e.target.value === "" || value > 0) {
        e.target.setCustomValidity("");
      } else {
        e.target.setCustomValidity("Please select a value that is greater than 0.");
      }
    }
    
    document.getElementById("float-field").addEventListener("input", checkIsPositive, false);
    

    JSFiddle here.

    Note that none of these solutions completely prevent the user from trying to type in invalid input, but you can call checkValidity or reportValidity to figure out whether the user has typed in valid input.

    Of course, you should still have server-side validation because the user can always ignore client-side validation.

提交回复
热议问题