如何使用AngularJS、JavaScript和Datepicker验证初始日期和结束日期?

How can I validate the initial and end date using AngularJS, JavaScript and Datepicker?

本文关键字:日期 验证 结束 Datepicker 何使用 AngularJS JavaScript      更新时间:2023-09-26

我目前正在参与一个使用Angular、JavaScript和c#的项目。在这个项目中,我们有一个用于创建项目的表单,包含以下字段:项目代码、描述、初始日期、结束日期、客户、技术和每小时的金额。

对于输入"初始日期"answers"结束日期",我使用了一个日期选择器,以便为用户提供一个日历,他们可以在其中选择所需的日期。我正在处理的问题是"结束日期"的验证。到目前为止,我在日历中禁用了当前日期之前的周末和天数。

我的想法是在"最终日期"的日历中禁用初始选定日期的前几天,因此它不能小于"初始日期"。

JavaScript和HTML代码:

(function() {
  angular.module('app.project')
    .controller('projectCreateCtrl', ['$state', 'alerts', 'project', projectCreateCtrl])
    .controller('DatepickerPopupDemoCtrl', ['$scope', DatepickerPopupDemoCtrl]);
  //Controller for the initial and end date
  function DatepickerPopupDemoCtrl($scope) {
    $scope.today = function() {
      $scope.vm.project.fechaInicio = new Date();
      $scope.vm.project.fechaFin = new Date();
    };
    $scope.today();
    $scope.inlineOptions = {
      customClass: getDayClass,
      minDate: new Date(),
      showWeeks: true
    };
    $scope.dateOptions = {
      dateDisabled: disabled,
      formatYear: 'yy',
      maxDate: new Date(2050, 1, 1),
      minDate: new Date(),
      startingDay: 1
    };
    // Disable weekend selection
    function disabled(data) {
      var date = data.date,
        mode = data.mode;
      return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6);
    }
    $scope.toggleMin = function() {
      $scope.minDate = $scope.minDate ? null : new Date();
    };
    $scope.toggleMin();
    $scope.open1 = function() {
      $scope.popup1.opened = true;
    };
    $scope.open2 = function() {
      $scope.popup2.opened = true;
    };
    $scope.setDate = function(year, month, day) {
      $scope.vm.project.fechaInicio = new Date(year, month, day);
      $scope.vm.project.fechaFin = new Date(year, month, day);
    };
    //Date format
    $scope.format = 'dd/MM/yyyy';
    $scope.popup1 = {
      opened: false
    };
    $scope.popup2 = {
      opened: false
    };
    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    var afterTomorrow = new Date();
    afterTomorrow.setDate(tomorrow.getDate() + 1);
    $scope.events = [{
      date: tomorrow,
      status: 'full'
    }, {
      date: afterTomorrow,
      status: 'partially'
    }];
    function getDayClass(data) {
      var date = data.date,
        mode = data.mode;
      if (mode === 'day') {
        var dayToCheck = new Date(date).setHours(0, 0, 0, 0);
        for (var i = 0; i < $scope.events.length; i++) {
          var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0);
          if (dayToCheck === currentDay) {
            return $scope.events[i].status;
          }
        }
      }
      return '';
    }
   
  }
  //Form controller
  function projectCreateCtrl($state, alerts, project) {
    var vm = this;
    vm.project = project;
    //Warning about the new project being saved
    vm.insert = function() {
      alerts.confirmSave('', 'Se guardará el proyecto 'n¿Está seguro?', vm.save);
    }
    //Back button
    vm.volver = function() {
      $state.go("app.project.index")
    }
    //saves project
    vm.save = function() {
      //projectService.saveProject(vm.project)
      project.$save(
        function() { //OK
          alerts.success("Se ha guardado el proyecto correctamente.", '', function() {
          });
        },
        function(error) { //ERROR
          alerts.error(error);
        });
    }
  }
})();
<div ng-controller="DatepickerPopupDemoCtrl">
  <div class="form-group row m-t">
    <label for="fechaInicio" class="col-md-1 control-label">Fecha Inicio</label>
    <div class="col-md-5">
      <div class="has-feedback" ng-class="{ 'has-error': (form.fechaInicio.$dirty || form.fechaInicio.$touched) && form.fechaInicio.$invalid, 'has-success':form.fechaInicio.$valid}">
        <p class="input-group">
          <input type="text" uib-datepicker-popup="{{format}}" ng-class="{ 'form-control input': form.fechaInicio.$valid, 'form-control input mandatory': !form.fechaInicio.$valid  }" id="fechaInicio" name="fechaInicio" readonly ng-model="vm.project.fechaInicio"
          is-open="popup1.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" min-date="minDate" />
          <span class="input-group-btn">
                                <button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>
                            </span>
        </p>
        <span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.fechaInicio.$valid" aria-hidden="true"></span>
        <span class="glyphicon glyphicon-remove form-control-feedback" ng-show="!form.fechaInicio.$valid && form.fechaInicio.$dirty" aria-hidden="true"></span>
        <div class="help-block" ng-messages="form.fechaInicio.$error" ng-show="form.fechaInicio.$dirty || form.fechaInicio.$touched">
          <div ng-messages-include="wwwroot/app/project/messages.html"></div>
        </div>
      </div>
    </div>
  </div>
  
  <div class="form-group row m-t">
    <label for="fechaFin" class="col-md-1 control-label">Fecha Fin</label>
    <div class="col-md-5">
      <div class="has-feedback" ng-class="{ 'has-error': (form.fechaFin.$dirty || form.fechaFin.$touched) && form.fechaFin.$invalid, 'has-success':form.fechaFin.$valid}">
        <p class="input-group">
          <input type="text" uib-datepicker-popup="{{format}}" ng-class="{ 'form-control input': form.fechaFin.$valid, 'form-control input mandatory': !form.fechaFin.$valid  }" id="fechaFin" name="fechaFin" readonly data-min-date="fechaInicio" ng-model="vm.project.fechaFin"
          is-open="popup2.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" />
          <span class="input-group-btn">
                                <button type="button" class="btn btn-default" ng-click="open2()"><i class="glyphicon glyphicon-calendar"></i></button>
                            </span>
        </p>
        <span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.fechaFin.$valid" aria-hidden="true"></span>
        <span class="glyphicon glyphicon-remove form-control-feedback" ng-show="!form.fechaFin.$valid && form.fechaFin.$dirty" aria-hidden="true"></span>
        <div class="help-block" ng-messages="form.fechaFin.$error" ng-show="form.fechaFin.$dirty || form.fechaFin.$touched">
          <div ng-messages-include="wwwroot/app/project/messages.html"></div>
        </div>
      </div>
    </div>
  </div>
</div>

翻译需要:

fechaInicio =初始日期

fechaFin = end date

提前感谢。

您已经使用minDate选项从现在开始禁用日历上的日期,您可以为fechaFin使用另一个$scope.dateOptions,其中minDatevm.project.fechaInicio

如果我得到你的问题是正确的,你想从初始日期Datepicker获取日期,然后给用户选择结束日期之后的日期。然后,只需保存选定的日期从"初始日期"的范围内,然后传递它作为"startDate"在"结束日期"的选项。阅读日期选择器文档从更好的理解这里

希望这已经解决了你的问题

这很简单。

为此,您需要在控制器中创建两个dateOptions。例如
$scope.fromOptions = {
  dateDisabled: disabled,
  formatYear: 'yy',
  maxDate: new Date(2050, 1, 1),
  minDate: new Date(),
  startingDay: 1
};
$scope.tillOptions = {
  dateDisabled: disabled,
  formatYear: 'yy',
  maxDate: new Date(2050, 1, 1),
  minDate: $scope.project.fechaInicio, // use from scope value here.
  startingDay: 1
};

,并分别在它们的日期拾取器选项中使用这些日期拾取器选项。

希望对你有帮助