使用AngularJS,如何验证date2< date1和date3> DATE2。
<form name='myForm'>
date1: <input type='text' name='date1' ng-model='obj.date1' required pattern='datePattern'/>
<div ng-show='obj.date2 > obj.date1'>date1 has to be greater than date2</div>
date2: <input type='text' name='date2' ng-model='obj.date2' required pattern='datePattern'/>
date3: <input type='text' name='date3' ng-model='obj.date3' required pattern='datePattern'/>
<input type='button' ng-click='saveData(obj)'/>
</form>
用例(用户输入):
答案 0 :(得分:1)
您可以使用函数来比较与日期关联的时间戳,如下所示:
function ctrl($scope){
$scope.compareDates=function( first, second){
dFirst=new Date(first);
dSecond=new Date(second);
console.log(first, second, dFirst, dSecond)
return dFirst.getTime()<dSecond.getTime();
}
}
然后,你可以简单地将它用于ng-show
<div ng-show='compareDates(obj.date1,obj.date2)'>date1 has to be greater than date2</div>
<div ng-show='compareDates(obj.date2,obj.date3)'>date3 has to be greater than date2</div>
这是为了比较日期,如果你想让第一个日期无效,如果第二个日期是之前/之后,你可以使用相同的函数并设置一个自定义$错误,如下所示:
$scope.invalidate=function(item){
console.log("invalidate")
$scope.myForm[item].$setValidity("notGoodEnough", false);
}
$scope.validate=function(item){
console.log("validate")
$scope.myForm[item].$setValidity("notGoodEnough", true);
}
你可以随时调用那些函数,在我的小提琴上,我在比较函数中添加了第三个参数来指定哪个字段必须通过比较验证,我让你检查:{ {3}}
玩得开心
答案 1 :(得分:1)
在进行比较的范围上定义一个函数。像这样:
date1: <input type='text' name='date1' ng-model='obj.date1'
required pattern='datePattern'/>
<div ng-show="compareDates(obj.date1, obj.date2)">
date1 has to be greater than date2
</div>
date2: <input type='text' name='date2' ng-model='obj.date2'
required pattern='datePattern'/>
JS:
function myController($scope){
$scope.compareDates = function(d1,d2){
/* convert to date object assuming the input d1 = 2013-08-15 */
/* or some other valid format */
d1 = new Date(d1);
d2 = new Date(d2);
return d1 < d2;
}
}
如果您的日期直接位于控制器的范围内,那么您不需要将日期传递给该函数。你可以这样做:
<div ng-show="compareDates()">date1 has to be greater than date2</div>
JS:
function myController($scope){
$scope.obj = {};
$scope.compareDates = function(){
/* convert to date objects assuming valid inputs */
return new Date($scope.obj.date1) < new Date($scope.obj.date2);
}
}