Angular 2 form validations start date <= end date

前端 未结 6 2002
孤街浪徒
孤街浪徒 2020-12-09 05:01

I\'m trying to add validations such that the end date can\'t be before the start date. Unfortunately I have no idea how to do that, and I didn\'t find any helpful advice in

6条回答
  •  一生所求
    2020-12-09 05:35

    Mine is angular7 + ngprime(for calendar)

    (*if you don't want ngprime just replace calendar part to others.)

    Refer below code for date validation.

    My code has additional validation that once start date is selected, I block previous days in end data's calendar so that the end date will be always later than that.

    if you don't want to block date, delete [minDate] part. it is also working.

    > Component

    export class test implements OnInit {
    
      constructor() { }
    
      defaultDate: Date = new Date();
      checkDate = true;
      form: FormGroup;
    
      today: Date = new Date(); //StartDate for startDatetime
      startDate: Date = new Date();  //StartDate for endDatetime
    
      initFormControls(): void {
        this.today.setDate(this.today.getDate());
        this.startDate.setDate(this.today.getDate()); //or start date + 1 day
    
        this.form = new FormGroup({
          startDatetime: new FormControl('', [Validators.required]),
          endDatetime: new FormControl('', [Validators.required])
        },
          { validators: this.checkDateValidation });
      }
    
      checkDateValidation: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
        try {
    
          let startingDatefield = control.get('startDatetime').value;
    
          this.startDate = new Date(startingDatefield); //new Date(startingDatefield).getDate()
          let endingDatefield = control.get('endDatetime').value;
    
          if (this.today >= startingDatefield) { //compare to current date 
            console.log("Please set a Start Date that is on or after Current Date and Time.");
            return { 'effectiveStartDatetime': false };
    
          } else
            if (startingDatefield > endingDatefield && endingDatefield) {
              console.log("Please set an End Date and Time that is after the Start Date and Time.");
              return {};
    
            } else {
              return {};
            }
        } catch (err) {
        }
      };
    
    
    
      onSubmit() {
    
        //if form is not valid
        if (!this.form.valid) {
          console.log(" Please fill in all the mandatory fields");
    
          // do sth
        return;
        }
    
    
        //if form is valid
        //do sth
    
      }
    
    
      ngOnInit() {
        this.initFormControls();
      }
    

    > HTML

    Start Date/Time"

    End Date/Time

提交回复
热议问题