Ivan Yurchenko
Ivan Yurchenko

Reputation: 3871

Angular custom reactive forms validator doesn't work

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

Upvotes: 0

Views: 550

Answers (2)

Ivan Yurchenko
Ivan Yurchenko

Reputation: 3871

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.

Upvotes: 0

Siju Samson
Siju Samson

Reputation: 507

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

Upvotes: 2

Related Questions