2

I have an angular form with custom aync validators I want to do some stuff if the form is invalid on load.

Here is the code

ngOnInit() {
        this.signupForm = this.fb.group({
          name: [
            'Prasad P',
            [Validators.required, Validators.maxLength(3)],
            ValidateUserNotTaken.createValidator(this.signupService)
          ],
          email: [
            '',
            [Validators.required, Validators.email],
            ValidateEmailNotTaken.createValidator(this.signupService)
          ]
        });
    
        // watch for status Changes
        this.signupForm.statusChanges.subscribe(status => {
          alert('Form Status Is ' + status);
    
          if(status === 'INVALID') {
            // do_stuff();
          }
        });

  }

The statusChange event never emits a value when loaded once I change anything in form then the event emits and everything works but I really want to know the form is invalid on loading.

I try to run updateValueAndValidity() but it always hangs to PENDING state.

The stackbliz Link : https://stackblitz.com/edit/angular-async-custom-validation-vlz43u?file=src%2Fapp%2Fapp.component.ts

1 Answer 1

0

I tested your code in stackblitz and I added updateValueAndValidity() after form has been created and it is working fine as expected. Please see this stackblitz.

The other alternative is you can patch your form values to your form to trigger the validation on page load. In the code below, I added setTimeout(() => { this.signupForm.patchValue(this.signupForm.value);}); to trigger the validation on page load. You need to add this after you created the form.

ngOnInit() {
    this.signupForm = this.fb.group({
      name: [
        'Prasad P',
        [Validators.required, Validators.maxLength(3)],
        ValidateUserNotTaken.createValidator(this.signupService)
      ],
      email: [
        '',
        [Validators.required, Validators.email],
        ValidateEmailNotTaken.createValidator(this.signupService)
      ]
    });

    //Added to trigger form validation
    setTimeout(() => {
      this.signupForm.patchValue(this.signupForm.value);
    });

    // watch for status Changes
    this.signupForm.statusChanges.subscribe(status => {
      alert('Form Status Is ' + status);

      if (status === 'INVALID') {
        // do_stuff();
        console.log('TEST');
      }
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

It works for OOTB validators but when it came to custom validators it always emits a PENDING status. I have updated the stckBliz link to show custom validator

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.