Malathy Venkatesan
Malathy Venkatesan

Reputation: 213

How to set input type date value of max="variable value"

Not able to get "today Date value to "max" attribute of input field", but able to fetch the value in the console.

Would you guys help me how to get value in the input field (i.e max="2018-08-21")

var todayDate =
      new Date().getFullYear() +
      "-" +
      ("0" + (new Date().getMonth() + 1)).slice(-2) +
      "-" +
      ("0" + new Date().getDate()).slice(-2);
    console.log(todayDate, "here");
 <div class="input-group">
    <input type="date" max="todayDate" />
 </div>

Upvotes: 1

Views: 826

Answers (3)

user4676340
user4676340

Reputation:

Since no-one is providing you with an Angular answer and instead rely on your locale to test it (which is dangerous to do), here it is : a custom validator that will check if the date is below the one you give to the validator. Here is a stackblitz demo

The validator :

export function notAfterToday(date: Date = new Date(Date.now())): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const selectedDate = new Date(control.value);
    return selectedDate && !isNaN(selectedDate.getTime()) && selectedDate.getTime() > date.getTime() ? { 'dateTooHigh': true } : null;
  };

Upvotes: 0

Krishna Rathore
Krishna Rathore

Reputation: 9687

use [max]

export class AppComponent  {

  todayDate = new Date('2018-08-21')

}

<div class="input-group">
  <input type="date" [max]="todayDate | date:'yyyy-MM-dd'" />
</div>

Upvotes: 0

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

As you are using Angular you can bind max with date as:

TS

todayDate = new Date().getFullYear() + "-" + ("0" + (new Date().getMonth() + 1)).slice(-2) + "-" + ("0" + new Date().getDate()).slice(-2);

HTML

<div class="input-group">
  <input type="date" [max]="todayDate" />
</div>

You can check stackblitz here

Upvotes: 3

Related Questions