angularjs - 如何在 Angular 中将 Select 更改为 ng-invalid

标签 angularjs validation

我使用选择输入字段在表单中显示到期月份和年份。当用户单击月份和年份时,ng-change 会触发函数 checkDate() 进行验证。我使用控制台返回日期是否有效。我还显示错误消息,指出过期日期无效。但是,即使表单无效,我也无法为选择元素指定无效状态。即使日期不正确,该类也会在 select 元素上从 ng-invalid 更改为 ng-valid,这最终使我的表单有效。如果选择字段无效,如何将无效类应用于选择元素?

HTML

<div>
    <label for="exp_year">Exp Year</label>
    <select id="exp_year" class="form-control" ng-model="exp_year" ng-change="checkDate()" required>
        <option value="" disabled><span class="pull-left">Year</span></option>
        <option value="{{ year }}" ng-repeat="year in years">{{ year }}</option>
    </select>
    <i class="material-icons pull-right select-icon">arrow_drop_down</i>
</div>

<small class="text-danger">{{errMessage}}</small>

JS

$scope.checkDate = function () {
    if (!($scope.exp_month && $scope.exp_month)) return;
    if ($scope.exp_month <= currentMonth && $scope.exp_year <= currentYear){
        console.log('this form is invalid')
        $scope.errMessage = 'Please enter a valid expiration date';
        return true
    } else {
        console.log('this form is valid')
        $scope.errMessage = '';
        return false
    }
}

最佳答案

有一种更好的方法来执行自定义验证,而不是通过添加 valid/invalid 类来验证表单输入:

使用$scope.formName.inputName.$setValidity("reason", false) ( Angular Docs )

因此,当您发现您的值无效(在您的情况下,月年组合已过期..)时,您可以将有效性设置为 false。当它再次有效时,为 true

您可以使用$scope.formName.$valid来了解您的表单是否有效。在此基础上,您可以执行进一步的操作。

Working plunker做了你的例子

关于angularjs - 如何在 Angular 中将 Select 更改为 ng-invalid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42980565/

相关文章:

angularjs - 如何实现带有中心内容栏的 AngularJS Google Images 样式行

javascript - angularJS中这些监视方法之间的区别?

javascript - Angular 2 - 'imports' 不存在于类型 'ComponentMetadataType' 中

使用 while 循环进行 Java 数据验证

PHP:检查 POST 数据的正确方法?

javascript - Angular ui 路线隐藏模式

javascript - ng-repeat 内的 ng-form 和 ng-repeat 外的提交按钮

javascript - 更改实时验证的错误消息

JavaScript/Html Pl/sql 验证器。

带有命名空间的 XML/XSD