Search code examples
angularangular8angular-validationangular-validator

Show form error without field blur in angular


In my application, I am trying angular validator. If the form is already filled with data, then the validation is perfect. But if no data is filled initially and if I click on the button, then it is not showing the errors. But if I click on some fields and blur, then it will show the error for that field.

How can I make the error show when click on the button?

validation.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ValidationService {

  constructor() { }

  static getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
    const config = {
      required: 'validation.required',
      minlength: `Minimum length is ${validatorValue.requiredLength}`,
      email: 'validation.email',
    };
    return config[validatorName];
  }
}

validation-message.component.ts

import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
import { ValidationService } from '../../services/validation/validation.service';
@Component({
  selector: 'app-errorMessages',
  template: `<div *ngIf="errorMessage !== null">{{errorMessage | translate}}</div>`
})
export class ValidationMessagesComponent {

  @Input() control: FormControl;

  constructor() { }

  /**
   * Function to get the form validation error message
   *
   * @readonly
   * @memberof ValidationMessagesComponent
   */
  get errorMessage() {
    for (const propertyName in this.control.errors) {
      if (this.control.errors.hasOwnProperty(propertyName) && this.control.touched) {
        return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
      }
    }
    return null;
  }
}

HTML portion to show the error

<app-errorMessages [control]="userForm.controls.userFullName" class="error-msg messages text-left text-danger"></app-errorMessages>

Button to initiate submit

<button type="button" class="btn btn-primary btn-lg btn-block"  ngIf="submitFlag" (click)="onSubmit()">Save</button>

Functions associated with submit

onSubmit(): any {
    // Component points data to the module and module points to the http service
    // use the retun value to trigger a toast Message.
    console.log(this.userForm);
    if (!this.validateUserForm()) {
      console.log('Show errors');
      return false;
    }
    this.userService.createNewUser(this.userForm.value);
  }

validateUserForm() {
    if (this.userForm.invalid) {
      return false;
    }
    return true;
  }

Solution

  • You want your conditional to look more like this:

     if (this.control.errors.hasOwnProperty(propertyName) && (this.control.touched || this.control.submitted)) 
    

    Then you also need to use the ngSubmit directive in a form element and change your button type to submit for it to work