js验证开始日期不能大于结束日期,Angularjs开始日期和结束日期验证

I am completely New to Angularjs and trying to validate 2 scenarios. I have 2 text boxes one with start date and the other with end date. I am checking

Show validation error on UI if start date is not greater than or equal to today. It should be today or any day after today.

Show validation error on UI if start date is greater than end date. End date should be greater than start date.

I tried the below code which did not work. Any suggestions please.

Html Code

Start Date:

id="startDate" ng-model="startDate" />

End Date:

id="endDate" ng-model="endDate"

ng-change='checkErr(startDate,endDate)' />

{{errMessage}}

js code

$scope.checkErr = function(startDate,endDate){

$scope.errMessage = '';

$scope.curDate = new Date();

if(startDate < endDate){

$scope.errMessage = 'End Date should be greate than start date';

return false;

}

if(startDate < curDate){

$scope.errMessage = 'Start date should not be before today.';

return false;

}

};

I have input type as text for both date controls.I am using bootstrap date picker.

解决方案

You have the logic reversed on the first bit and you have to construct a new date from startDate to compare to today's date. Also you set curDate to the scope, $scope.curDate = new Date() but then you were referencing it as curDate without the $scope so it was undefined. Lastly, you need to cast stateDate and endDate to a date as well. Otherwise you're just comparing strings.

$scope.checkErr = function(startDate,endDate) {

$scope.errMessage = '';

var curDate = new Date();

if(new Date(startDate) > new Date(endDate)){

$scope.errMessage = 'End Date should be greater than start date';

return false;

}

if(new Date(startDate) < curDate){

$scope.errMessage = 'Start date should not be before today.';

return false;

}

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值