0

I have a userForm group which has keys name, email and phone. Also I have a onValueChanged function which one subscribes to form changes and validate data.

 buildForm(): void {
    this.userForm = this.fb.group({
      'name': ['', [
          Validators.required,
        ]
      ],
      'email': [''],
      'phone':    ['', Validators.required]
    });

this.userForm.valueChanges
  .subscribe(data => this.onValueChanged(data));

Also I have a submit button, but if user doesn't print any data and submit form my errors doesn't show. How can I fix it?

onSubmit() {
    this.submitted = true;
}

This is my errors:

formErrors = {
    'name': '',
    // ...
  };

  validationMessages = {
    'name': {
      'required':      'Name is required.',
      'minlength':     'Name must be at least 4 characters long.',
      // ...
    },
    // ...
  };
}

My onValueChanged function:

 onValueChanged(data?: any): void {
    if (!this.registrationForm) return;
    const form = this.registrationForm;

    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control: any = form.controls[field];

      if (control && control.dirty && !control.valid) {
        const messages: string = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

I use my validation in template like this:

<div [ngClass]="formErrors.email ? 'has-danger' : '' ">
    <label for="email">Email <span class="text-danger">*</span></label>
    <input type="email" formControlName="email"  id="email">
    <div class="form-control-feedback">{{formErrors.email}}</div>
</div>

1 Answer 1

1

You need to write ngif statements in your component.html(html or your html file). Such as below for phone formControl:

  <div *ngIf="!phone.valid && (phone.touched || submitted)">Required</div>

Added phone.touched, so that error displays only after formControl has been touched by user.

Added submitted, so that error displays only after user has attempted to submit form.

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

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.