这是HTML代码。 (表格名称为“addForm”)
<fieldset>
<label>Start Date</label>
<input tabindex="3" class="date-picker" name="startDate" type="text" id="datepicker" ng-model="startDate" ng-required="true">
<span style="color:red" ng-show="addForm.startDate.$dirty && addForm.startDate.$invalid">
<span ng-show = "addForm.startDate.$error.required">Start date is required.</span>
<span ng-show="addForm.startDate.$error.invalidDat">Invalid Date</span>
</span>
</fieldset>
<fieldset>
<label>End Date</label>
<input tabindex="4" class="date-picker" name="endDate" type="text" id="datepicker2" ng-model="endDate" ng-required="true">
<span style="color:red" ng-show="addForm.endDate.$dirty && addForm.endDate.$invalid">
<span ng-show = "addForm.endDate.$error.required">End date is required.</span>
<span ng-show="addForm.endDate.$error.invalidDate">Invalid Date</span>
<span ng-show="addForm.startDate.$error.endBeforeStart">End date must be on or after start date.</span>
</span>
</fieldset>
Angular JS控制器如下,
tournamentAddApp.controller('tournamentAddController', function($scope) {
$scope.$watch('startDate', validateDates);
$scope.$watch('endDate', validateDates);
function validateDates() {
if (!$scope.model) return;
if ($scope.addForm.startDate.$error.invalidDate || $scope.addForm.endDate.$error.invalidDate) {
$scope.addForm.startDate.$setValidity("endBeforeStart", true);
} else {
var EndDate = new Date($scope.endDate);
var StartDate = new Date($scope.startDate);
$scope.addForm.StartDate.$setValidity("endBeforeStart", EndDate >= StartDate);
}
}
});
大多数预期的验证都无法正常工作。
例如,如果表单中的默认日期被完全删除并且该字段留空,则会显示相应的错误消息(“需要开始日期”) )。然后,当使用日期选择器选择日期时,错误消息不会消失。
它会一直保持到使用键盘输入日期为止。