角度中的错误消息/表单验证

时间:2015-10-10 20:44:42

标签: angularjs forms

我是棱角分明的新人。我有一个表格,我需要检查一个人是否14岁或以上。如果此人的注册人数超过14,我需要显示错误消息。

我的控制器中有一个功能来检查这个。但我不知道如何为此编写错误消息。

以下代码:

<form name="myForm" >
    <input type="date" name="birthdate" ng-model="birthdate">
    Is person older than 14: {{minAge(birthdate)}}<br/>
    <small class="error"
           ng-show="myForm.birthdate.$error.minAge">
         You must be 14 years or older
    </small>
</form>

<script>
    var app = angular.module("myApp", []);
    app.controller('Ctrl', function ($scope) {
        $scope.birthdate = new Date(2000,1,1);
        $scope.minAge = function calculateAge(birthday) {
            var ageDifMs = Date.now() - birthday.getTime();
            var ageDate = new Date(ageDifMs);
            return Math.abs(ageDate.getUTCFullYear() - 1970) > 14;
        }
    });

</script>

2 个答案:

答案 0 :(得分:0)

如果为此检查编写自定义指令,情况会更好。您可以重用现有代码,使其如下所示:

app.directive('minAge', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelController) {
            var minAge = scope.$eval(attrs.minAge);
            ngModelController.$validators.minAge = function(value) {
                var ageDifMs = Date.now() - new Date(value);
                var ageDate = new Date(ageDifMs);
                return Math.abs(ageDate.getUTCFullYear() - 1970) > minAge;
            };
        }
    };
});

并且用法是:

<form name="myForm">
    <input type="date" name="birthdate" ng-model="birthdate" min-age="14"> Is person older than 14: {{minAge(birthdate)}}
    <br/>
    <small class="error" ng-show="myForm.birthdate.$error.minAge">
        You must be 14 years or older
    </small>
</form>

演示: http://plnkr.co/edit/1sUFL1kNp2UI7dyFogVk?p=preview

答案 1 :(得分:0)

看看这个:

&#13;
&#13;
var app = angular.module("myApp", []);
app.controller('Ctrl', function ($scope) {
    $scope.validDate = function(){
        var d = new Date();
        return new Date(d.getUTCFullYear(), d.getMonth(), d.getDate() - (14*365));
    };
  
    $scope.birthdate = new Date();
    $scope.minValidDate =  $scope.validDate();
  
    $scope.checkDate = function () {
        $scope.isValidDate = (new Date($scope.birthdate).getTime() <= $scope.validDate().getTime());
    };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp" ng-controller="Ctrl" name="myForm" >
    <input type="date" name="birthdate" ng-model="birthdate" ng-change="checkDate()">
    Is person older than 14, min valid date is: {{minValidDate}}<br/>
    <small class="error"
    ng-show="!isValidDate">
    You must be 14 years or older
</small>
</form>
&#13;
&#13;
&#13;