Home > OS >  Multiple stage form validation angular
Multiple stage form validation angular

Time:11-04

I am working on the form with validation on multiple stages, few elements validate normally, few elements validate on blur and other elements validate on submit. Validations are not working correctly. If someone knows better way of handling it then please let me know. Thanks

Here is my code:

constructor(
  private changeDetectorRef: ChangeDetectorRef,
  private el: ElementRef,
  private _snackBar: MatSnackBar ) {
  this.form = new FormGroup({});
  this.form.addControl(`firstname`, new FormControl(''));
  this.form.addControl(`lastname`, new FormControl(''));
  this.form.addControl(`title`, new FormControl('', 
  Validators.compose([Validators.required])));
this.form.addControl(
  `email`,
  new FormControl(
    '',
    Validators.compose([
      Validators.required,
      Validators.pattern('^[a-zA-Z0-9_. -] @[a-zA-Z0-9-] .[a-zA-Z0-9-.] $'),
    ])
  )
);
this.form.addControl(
  `phoneNumber`,
  new FormControl('', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')]))
);
this.form.addControl(
  `termsAndConditions`,
  new FormControl('', Validators.compose([Validators.required]))
);

this.changeDetectorRef.markForCheck();
}


addValidation() {
this.form.controls['firstname'].setValidators([Validators.required, Validators.minLength(2)]);
this.form.controls['lastname'].setValidators([Validators.required, Validators.minLength(2)]);
 }
 removeValidation() {
   this.form.controls['firstname'].setValidators([]);
   this.form.controls['lastname'].setValidators([]);
}

 onSubmit() {
    this.addValidation();
    // rest of my logic
}

onCancelBtnClick() {
  this.form.reset();
  this.removeValidation();
}

CodePudding user response:

There is a cleaner way of doing it. Make some changes in the code in the constructor and then you will not need addValidation and removeValidation methods. Forexample here we are applying validations on firstname and lastname on submit and on email on blur.

  this.form.addControl(`firstname`, new FormControl('', {
  validators: Validators.compose([Validators.required, Validators.minLength(2)]), updateOn: 'submit'
}));
this.form.addControl(`lastname`, new FormControl('', {
  validators: Validators.compose([Validators.required, Validators.minLength(2)]), updateOn: 'submit'
}));
this.form.addControl(`title`, new FormControl(''));
this.form.addControl(
  `email`,
  new FormControl(
    '',
    Validators.compose([
    '', {
    validators: Validators.compose([
      Validators.required,
      Validators.pattern('^[a-zA-Z0-9_. -] @[a-zA-Z0-9-] .[a-zA-Z0-9-.] $'),
    ])
    ]), updateOn: 'blur'
  }
  )
);
  • Related