0

I'm wondering if it is possible to set an invalid date string to an HTML5 date input after some JS check, for example "Today" instead of displaying XX-XX-XXXX date?

Note that I'm working with angular-1.6 that uses it's built-in directive that makes this hack harder to realize.

<input id="dateNative"
   type="date"
   ng-model="date.selectedDate"
   min="{{minDate | date:'yyyy-MM-dd'}}">


function Controller($scope, $log, $element, $document) {
  $scope.date = {};
  $scope.minDate = new Date();

  this.$postLink = () => {
    this.dateCtrl = angular.element($document[0].getElementById('dateNative')).controller('ngModel');
    this.dateCtrl.$parsers.unshift(date => {
      if (moment(new Date()).isSame(date, 'day')) {
        return 'Immediately';
      }
      return date;
    });
  };
}

2 Answers 2

1

Try changing the input type to text

this.dateCtrl.$parsers.unshift(date => {
  if (moment(new Date()).isSame(date, 'day')) {
    $element[0].type = 'text';
    return 'Immediately';
  }
  $element[0].type = 'date';
  return date;
});
Sign up to request clarification or add additional context in comments.

4 Comments

Like this I will lose the input date, specially the mobile experience the user will enter date manually ...
Well can't have it both ways...invalid value and keep date type. Will have to think of another way to do it then. Perhaps using <label for="dateNative">
Thank you, but this is not suitable for me, the UI team won't accept to add label to display selected date :D
Idea was only use the label for invalid values (over top input).... otherwise it won't be visible
1

The element can use interpolation to define the input type

<input id="dateNative"
   type="{{date.type}}"
   ng-model="date.selectedDate"
   min="{{minDate | date:'yyyy-MM-dd'}}" />
$scope.date.type = "text";
$scope.date.selectedDate = "Immediately";

3 Comments

Thank you, this is helpful, but it just need some work to make it more dynamic :)
I recommend that dynamic type changing be done inside a custom directive that is attached to the <input> element. Avoid doing DOM manipulation in a view controller.
For an example of a directive that changes an <input> type, see show-password directive on <input> element in angularjs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.