我无法验证我的日期字段。
这个想法是当用户输入日期时验证卡是否过期。我制定了这个指令,但我对于角度指令有点迷失。
checkOut.directive('cardDateExpiration', function() {
return {
require: 'ngModel',
link: function(date) {
var currentDate = new Date();
var m, y, d;
if (/^\d{2}\/\d{2}$/.test(date)) {
m = date.substring(0, 2) - 1;
y = 20 + date.slice(-2);
d = new Date(y, m);
} else if (/^\d{2}\/\d{4}$/.test(date)) {
m = date.substring(0, 2) - 1;
y = date.slice(-4);
d = new Date(y, m);
} else if (/^\d{4}$/.test(date)) {
m = date.substring(0, 2) - 1;
y = 20 + date.slice(-2);
d = new Date(y, m);
}
return currentDate > d;
}
}
});

<div class="large-6 columns sd-items-form">
<label>
<input id="expiry_date" maxlength="5" name="datacard" card-date-expiration ng-disabled="" class="sd-field sd-txt-center p-l-0" ng-model="form.data.datacard" type="text" type placeholder="MM / YY" required></input>
</label>
<div class="error" ng-if="checkoutPayment.$submitted || checkoutPayment.datacard.$touched" ng-messages="checkoutPayment.datacard.$error">
<p class="text-msg" ng-message="required">Not valid date credit card</p>
</div>
</div>
&#13;
答案 0 :(得分:1)
我有一个如何在角度对角度进行自定义验证的示例:http://jsfiddle.net/fortesl/2uv6xmjL/6/ 我正在使用momentjs验证日期,我推荐,但如果你愿意,你也可以解析输入字符串(我不推荐)。代码如下所示:
app.directive('dateFieldValidator', [function () {
var validateDate = function (date, format) {
if (!date.length) {
return true;
}
return moment(date, format.toUpperCase(), true).isValid();
};
return {
restrict: 'A',
require: 'ngModel',
scope: {
dateFormat: '@'
},
link: function (scope, elem, attrs, ngModelCtrl) {
//For DOM -> model validation
ngModelCtrl.$parsers.unshift(function (value) {
var valid = validateDate(value, scope.dateFormat);
ngModelCtrl.$setValidity('validDate', valid);
return valid ? value : undefined;
});
//For Model Update --> DOM
ngModelCtrl.$formatters.unshift(function (value) {
var valid = validateDate(value, scope.dateFormat);
ngModelCtrl.$setValidity('validDate', valid);
return value;
});
}
};
}]);
这是一个使用指令的示例html:
<div ng-app="dateApp">
<div ng-controller="DateController as dateCtrl">
<form name="dateForm" novalidate
ng-submit="dateCtrl.setDate(dateForm.dateInput.$valid); dateForm.dateInput.$setPristine();">
Enter date:
<input name="dateInput" ng-model="dateCtrl.date" date-format="{{dateCtrl.format}}"
date-field-validator placeholder="{{dateCtrl.format}}">
<button ng-disabled="dateForm.dateInput.$pristine">Submit</button>
</form>
</div>
样本控制器:
var app = angular.module('dateApp', []);
app.controller('DateController',function(){ var self = this;
self.format = 'MM/DD/YYYY';
self.date = '';
self.setDate = function (valid) {
if (valid) {
window.alert('You entered a valid Date: ' + self.date);
} else {
window.alert('!!!!!!!!!! WARNING: INVALID DATE !!!!!!!!!');
}
self.date = '';
}
})