Angular JS字段仅对其值为tan tan

时间:2016-04-16 09:21:16

标签: javascript jquery angularjs validation

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

$scope.validCats = "0";

HTML:

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

用户无法直接更改其值。如果值为零或更小,我需要显示验证错误(即字段无效)。 simple只有在值大于零时才有效

请帮帮我。

1 个答案:

答案 0 :(得分:2)

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&amp;在type="number"

时,Firefox不是该文本字段的微调器
.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
}