0

I'm trying to implement a custom angular validator for date range checking.

The validator itself works properly and returns a validation error. However, nothing seems to be happening at the client side - no errors are being shown and the form is considered to be valid. I've tried various changes to this code, with no joy.

Any ideas on what to try?


Html:

<div class="alert-danger" *ngIf="form.controls.creditCheckDate.errors?.dateRange">
    Date should be from 1/1/2000 to Today.
</div>

.ts:

const controlsConfig = {
    creditCheckDate: ['', [Validators.required,
                           CustomValidators.dateRange(new Date(2000, 1), new Date(Date.now()))]]
};

return this.fb.group(controlsConfig);

Validator:

static dateRange(minDate: Date | null, maxDate: Date | null): ValidatorFn {
    return (c: AbstractControl): ValidationErrors | null => {
        const validationError = { dateRange: true };

        if (!c.value) {
            return null;
        }

        const timestamp = Date.parse(c.value);
        if (isNaN(timestamp)) {
            return validationError;
        }

        const date = new Date(timestamp);
        if ((minDate && minDate > date) || (maxDate && maxDate < date)) {
            return validationError;
        }

        return null;
    };
}
3
  • try adding *ngIf="NameOfYourForm?.hasError('dateRange')" Commented Jun 25, 2020 at 17:23
  • @Kardon63 Thanks, unfortunately it still doesn't work. I tried to log the form into console on the control change event and the form is considered valid even though the validator returns error, so there's no error in the control. Commented Jun 25, 2020 at 17:26
  • Could you create a stackblitz? Commented Jun 25, 2020 at 17:45

2 Answers 2

2

Please have a look at my code.

HTML

<form [formGroup]="testForm">
  <div class="row">
    <div class="col-xs-12 col-12 col-md-4 form-group">
      <input
        type="text"
        placeholder="Datepicker"
        class="form-control"
        bsDatepicker
        formControlName = "date"
      />
    </div>
    <div *ngIf="testForm.controls.date.invalid && (submitted)" class="text-danger">
        <small *ngIf="testForm.controls.date.errors?.required">
           Date is required
         </small>
       <small *ngIf="testForm.controls.date.errors?.dateRange">
         Date is invalid
       </small>
     </div>
  </div>
  <button type="button" (click)="onSubmit()">Submit</button>
</form>

TS

 import { Component } from "@angular/core";
    import {
      AbstractControl,
      FormGroup,
      FormControl,
      ValidationErrors,
      ValidatorFn,
      Validators
    } from "@angular/forms";
    
    @Component({
      selector: "app-root",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      testForm: FormGroup;
      submitted: boolean;
    
      constructor() {
        this.testForm = new FormGroup({
          date: new FormControl("", [Validators.required, this.dateRange(new Date(2000, 1), new Date(Date.now()))])
        });
        this.submitted = false;
      }
    
      dateRange(minDate: Date | null, maxDate: Date | null): ValidatorFn {
        return (c: AbstractControl): ValidationErrors | null => {
          const validationError = { dateRange: true };
    
          if (!c.value) {
            return null;
          }
    
          const timestamp = Date.parse(c.value);
          if (isNaN(timestamp)) {
            return validationError;
          }
    
          const date = new Date(timestamp);
          if ((minDate && minDate > date) || (maxDate && maxDate < date)) {
            return validationError;
          }
    
          return null;
        };
      }
    
      onSubmit() {
        this.submitted = true;
        console.log(this.testForm);
      }
    }

I have tried your code in code sandbox, and there it seems to work fine. https://codesandbox.io/s/suspicious-http-11288

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

2 Comments

Thank you very much for taking your time to make that! I was really confused on why does that one work whereas mine doesn't. I started to check what's different between my code and sandbox you created and found out that someone was resetting all errors for the form within another validator afterwards. Your answer helped me to figure that out, thanks!
Glad it helped !
0

So it turned out that I didn't provide all the info. The issue was that someone was resetting all errors for the form within other validator. Which is a terrible way to do things, as I couldn't find it for such a long time, but it was there. When I found and fixed it everything started to work as expected.

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.