1

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>
2
  • You Javascript should be before HTML Commented Aug 21, 2018 at 6:37
  • You should use momentjs when you work with dates. Commented Aug 21, 2018 at 6:41

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

@MalathyVenkatesan great you can upvote & accept answer :)
0

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>

Comments

0

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;
  };

Comments

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.