目前我有以下代码

<input type="number" />

结果是这样的

右边的选择器允许数字变为负数。我该如何预防呢?

我对使用type="number"有疑问,它造成的问题比它解决的要多,我无论如何都要检查它,所以我应该回到使用type="text"吗?


当前回答

试试这个:

Yii2 : Validation rule 

    public function rules() {
    return [
['location_id', 'compare', 'compareValue' => 0', 'operator' => '>'],
        ];
}

其他回答

<输入类型=“数字” 分钟=“1” 步数=“1”>

你可以通过以下方法将负输入转化为正数:

<input type=“number” onkeyup=“if(this.value<0){this.value= this.value * -1}”>

这取决于你想要多精确。如果你想只接受整数,那么:

<输入类型=“数字” 分钟=“1” 步数=“1”>

例如,如果你想要浮点数,小数点后有两位数字:

<输入类型=“数字” min=“0.01” 步数=“0.01”>

其他解决方案是使用Js使它为正(min选项可以被禁用,当用户输入smth时无效)负if是不必要的,on('keydown')事件也可以使用!

let $numberInput =  $('#whatEverId');
$numberInput.on('change', function(){
    let numberInputText = $numberInput.val();
    if(numberInputText.includes('-')){
        $numberInput.val(Math.abs($numberInput.val()));
    }
});

这取决于你想要的是int还是float字段。下面是这两款游戏的外观:

<input type="number" name="int-field" id="int-field" placeholder="positive int" min="1" step="1">
<input type="number" name="float-field" id="float-field" placeholder="positive float" min="0">

int字段附加了正确的验证,因为它的最小值是1。然而,float字段接受0;为了解决这个问题,你可以添加一个约束验证器:

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这里。

注意,这些解决方案都不能完全阻止用户尝试输入无效的输入,但是您可以调用checkValidity或reportValidity来确定用户是否输入了有效的输入。

当然,您仍然应该进行服务器端验证,因为用户总是可以忽略客户端验证。