我不能在我的表单中使用angularjs
来允许将来的日期这是我的HTML:
<div ngCloak ng-app="laurelMoney" ng-controller="myCtrl">
<form name="userForm">
<div class="form-group">
<input type='date' id="trandate" class="form-control" ng-model="trandate" required ng-class="{ 'has-error' : userForm.trandate.$error }" />
<p ng-show="userForm.trandate.$error" class="help-block">Transaction can't be in future</p>
</div>
<a href="#" class="btn btn-primary btn-sm btn-block" ng-click="submitForm()" type="submit">Add Transaction</a>
</form>
我的javascript是Ñ
angular.module('laurelMoney', [])
.controller('myCtrl', function($scope) {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = yyyy + '-' + mm + '-' + dd;
document.getElementById("trandate").setAttribute("max", today);
$scope.submitForm = function() {
if ($scope.userForm.$valid) {
alert('our form is amazing');
} else {
console.log("Error");
}
};
});
当日历弹出时,此功能正常。未来的日期都被禁用。但我可以手动将其更改为日期输入框中的未来日期。
系统允许在将来的日期提交。如何解决这个问题?
感谢。
答案 0 :(得分:5)
嗯,根据您的问题我可以理解您只是尝试抛出错误消息或禁止用户选择未来日期,是不是?那么,你走了:
备注:强>
Angular
版本已完全过时,因此可能无法按预期运行; ngCloak
应为ng-cloak
; attribute
中添加名称 input
进行验证; ngSubmit
提交表单,而不是ng-click
。button
为form
,您可以停用invalid
,而不是在controller
进行此检查; $scope.max = new Date()
并在您的视图中调用它; 这是一个完整的例子:
(function() {
'use strict';
angular
.module('laurelMoney', [])
.controller('myCtrl', myCtrl);
myCtrl.$inject = ['$scope'];
function myCtrl($scope) {
$scope.max = new Date();
}
})();
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body ng-app="laurelMoney">
<div ng-cloak ng-controller="myCtrl">
<form name="userForm" novalidate ng-submit="submitForm()">
<div class="form-group" ng-class="{ 'has-error' : userForm.trandate.$error }">
<input type="date" name="trandate" class="form-control" required max="{{max}}" ng-model="trandate">
<p ng-if="userForm.trandate.$touched && userForm.trandate.$error.required" class="help-block">Transaction is required</p>
<p ng-if="userForm.trandate.$error.date" class="help-block">Transaction should be a valid date</p>
<p ng-if="userForm.trandate.$error.max" class="help-block">Transaction can't be in future</p>
</div>
<button type="submit" class="btn btn-primary btn-sm btn-block" ng-disabled="userForm.$invalid">Add Transaction</button>
</form>
<pre ng-bind="userForm.trandate.$error | json"></pre>
</div>
</body>
</html>