Kan
Kan

Reputation: 539

Angular formGroup, have specific validator for each value

I have a form with 3 value.

 this.testForm = this.formBuilder.group(
      {
        beginDate: ['', [Validators.required]],
        endDate: ['', [Validators.required]],
        username: ['', [Validators.required]],
      },
      { }
    );

I want to put a specific validator for each value so beginDate should be 01.xx.xxxx (should always be the first of the month) endDate should be 25.xx.xxxx (should always be the 25 of the month) username should start with the 'p' letter.

What is the better way to do that ? I can create a validators and check with if/else but it isn't really pretty:

this.testForm = this.formBuilder.group(
      {
        beginDate: ['', [Validators.required]],
        endDate: ['', [Validators.required]],
        username: ['', [Validators.required]],
      },
      { validator: this.checkValue}
    );

Is it a better way to have a validator for each value of my fromgroup ?

Upvotes: 0

Views: 448

Answers (1)

Eldar
Eldar

Reputation: 10790

You can try a custom validator like below.


function dayOfMonthValidator(date: number): ValidatorFn {
  return (control: AbstractControl): {
    [key: string]: boolean
  } | null => {
    let {  value } = control;
    if (Object.prototype.toString.call(control.value) !== "[object Date]")
      value = Date.parse(value);
    return value.getDate() === date 
      ? null 
      : { "dayOfMonth": true   }
  };
}

and use it like below :

this.testForm = this.formBuilder.group(
      {
        beginDate: ['', [Validators.required,this.dayOfMonthValidator(1)]],
        endDate: ['', [Validators.required,,this.dayOfMonthValidator(25)]],
        username: ['', [Validators.required]],
      },      
    );

Stackblitz

Upvotes: 1

Related Questions