【问题标题】:Angular JS field valid only its value greater tan zeroAngularjs 字段仅有效其值大于零
【发布时间】:2016-08-08 07:48:10
【问题描述】:

我的表单中有以下文本框,当用户更改类别(选择框)时,它的值会动态变化。最初,它被设置为 0。

$scope.validCats = "0";

HTML:

<input ng-model="validCats" value=""  type="text" class="form-control input-text phone_number" required >

用户不能直接更改其值。如果值为零或更小,我需要显示验证错误(即字段无效)。简单,仅当值大于零时才有效

请帮帮我。

【问题讨论】:

    标签: javascript jquery angularjs validation


    【解决方案1】:

    type 更改为number 并添加以下内容:

    <input ng-model="validCats" type="number" min="1"
        class="form-control input-text phone_number" required >
    <span ng-show="validCats === 0 || validCats === '0'">Invalid categories</span>
    

    $scope.validCats = 0 // instead of "0"
    

    您还应该设置一个 CSS,以便 Chrome 和 Firefox 在 type="number" 时不会为该文本字段设置微调器

    .input-text {
        -moz-appearance: textfield;
    }
    .input-text::-webkit-outer-spin-button {
        -webkit-appearance: none
        margin: 0
    }
    .input-text::-webkit-inner-spin-button {
        -webkit-appearance: none
        margin: 0
    }
    

    您应该在输入字段中添加 min="1" 验证器(仅限 HTML5)以防止提交,您还可以在方法中添加检查,如下所示:

    // called from ng-submit
    $scope.onFormSubmit = function() {
        // just additional check
        if ($scope.validCats === 0 || $scope.validCats === "0") {
            return false;
        }
    
        // do other thing after form submission
    }
    

    【讨论】:

    • 但表单仍然会提交非空数字字段
    猜你喜欢
    • 2020-06-16
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多