AngularJS 中负数值的验证

3

我正在使用input type="number",但我在文本框中得到了上下值条的视图。如何避免这种情况?
如何验证输入文本框中的负值?如果我输入一个负值,则应显示适当的错误消息。


您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - dfsq
重复的问题:https://dev59.com/pG865IYBdhLWcg3wfemU 对于负数,您可以编写一个过滤器来捕获减号并给出错误消息。 - katmanco
1个回答

3
但是在文本框中,我得到了上下值条的视图。如何避免这种情况发生? 您可以使用简单的CSS在某些浏览器中删除那些微调按钮:
input[type='number'] {
    -moz-appearance:textfield;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

(感谢这个答案)但它在IE中不起作用。

现在的真正问题是,如何验证用户输入?在这种情况下,Angular解决方案是创建额外的验证指令。这是我最近编写的一个简单的指令:

angular.module('demo', []).directive('positive', [function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            if (!ctrl) return;
            ctrl.$validators.positive = function(value) {
                return value && value >= 0;
            };
        }
    };
}]);
input[type='number'] {
    -moz-appearance:textfield;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

.error {color: brown;}
<script src="https://code.angularjs.org/1.3.0/angular.js"></script>

<div ng-app="demo">
    
    <form name="paymentForm">
        <input type="number" name="amount" ng-model="amount" positive />
    </form>
    
    <div class="error" ng-show="paymentForm.amount.$error.positive">Amount should be positive number.</div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接