Search code examples
angularangular-reactive-formsangular-validation

Angular 4 custom validation error message


I'm working on a form using Angular 4 (reactive forms), my problem is I cant show individually the error messages for the email address field.

I'm trying this format but no luck.

<div *ngIf="name.invalid && (name.dirty || name.touched)"
     class="alert alert-danger">

  <div *ngIf="name.errors.required">
    Name is required.
  </div>
  <div *ngIf="name.errors.minlength">
    Name must be at least 4 characters long.
  </div>
  <div *ngIf="name.errors.forbiddenName">
    Name cannot be Bob.
  </div>

This is my sample code

register.component.ts

constructor(private fb: FormBuilder) { 

    this.rForm = fb.group({

    'account': [null, Validators.required],
    'company': [null, Validators.required],
    'website': '',
    'email': [null, Validators.compose([Validators.email, Validators.required])],
    'phone': [null, Validators.required],

    })

  }

register.component.html

<div class="col-md-6">
    <label>Email Address</label>
    <input type="email" name="email" class="form-control" formControlName = "email">
    <span class="text-danger" *ngIf="!rForm.controls['email'].valid && rForm.controls['email'].touched">This field is required. Please provide a valid email address.</span>

Thanks.


Solution

  • First, you should use rForm.get('email').valid instead of rForm.controls['email'].valid.

    An easier way to do it is to add the following code to your class:

    get email() { return this.rForm.get('email'); }
    

    That way instead of using rForm.get('email').valid in your template, you can use email.valid.

    I have put together a working plnkr here (http://plnkr.co/edit/bDANlDxej3hAKQFx9sra?p=preview)