Angular 5 ngx-bootstrap form validation

Mike Glaz picture Mike Glaz · Nov 17, 2017 · Viewed 10.4k times · Source

I'm reading Ari Lerner's ng-book on Angular 5. I'm using ngx-bootstrap and Bootstrap 4. Form validation doesn't seem to be working the way Mr. Lerner implements. I'm not sure if this is a limitation of ngx-bootstrap...anyone know?

edit Ok, I removed ngx-bootstrap and just loaded up the MaxCDNs for Bootstrap 4 and I have the same problem. The error message is not appearing.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { RegistrationFormComponent } from './registration-form/registration-form.component';
import {
  FormsModule,
  ReactiveFormsModule,
  FormBuilder,
  FormGroup
} from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    RegistrationFormComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

registration-form.component.ts

import { Component, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';

@Component({
  selector: 'app-registration-form',
  templateUrl: './registration-form.component.html',
  styleUrls: ['./registration-form.component.scss']
})
export class RegistrationFormComponent implements OnInit {
  regForm: FormGroup;
  // name: AbstractControl;

  constructor(fb: FormBuilder) {
    this.regForm = fb.group({
      'name': ['', Validators.required],
      // 'email': ['', Validators.required],
      // 'password': ['', Validators.required],
      // 'password_confirmation': ['', Validators.required]
    });

    // this.name = this.regForm.controls['name'];
  }

  ngOnInit() {
  }

  onSubmit(value: string): void{
    console.log(value);
  }
}

registration-form.component.html

<div class="row justify-content-center">
  <h1>New User</h1>
</div>

<div class='row justify-content-center'>
  <div class='col-6'>
    <form [formGroup]='regForm'
    (ngSubmit)="onSubmit(regForm.value)"
    [class.error]="!regForm.valid && regForm.touched"
    >
      <div class='form-group'
        [class.error]="!regForm.get('name').valid && regForm.get('name').touched">
        <label>Name</label>
        <input type="text" class='form-control' [formControl]="regForm.controls['name']">
        <div *ngIf="regForm.controls['name'].hasError('required')" class="invalid-feedback">Name is required</div>
      </div>
      <div class='form-group'>
        <label>Email</label>
        <input type="email" class='form-control'>
      </div>
      <div class='form-group'>
        <label>Password</label>
        <input type="password" class='form-control'>
      </div>
      <div class='form-group'>
        <label>Confirmation</label>
        <input type="password" class='form-control'>
      </div>
      <button type="submit" class='btn btn-default'>Submit</button>
    </form>
  </div>
</div>

Answer

ChrisEenberg picture ChrisEenberg · Nov 27, 2017

It'll work by adding a class="was-validated" to the outer most div as per documentation: link to bootstrap form validation. This will initiate the validation on your fields. Also, remember to flag your inputs with required and turn of default html validation by passing the form a novalidate

Example of working code:

<div class="container" class="was-validated">
  <form [formGroup]="regForm" novalidate (ngSubmit)="submitForm(regForm.value)">
    <div class="row justify-content-center">
      <div class="form-group col-6">
        <label class="col-12 col-form-label" for="email">Email</label>
        <input type="email" placeholder="Email address" class="form-control form-control-lg col-12" id="email" [formControl]="regForm.controls['email']"
          required>
        <div class="invalid-feedback">
          Please provide a valid email.
        </div>
      </div>
    </div>

    <div class="row justify-content-center">
      <div class="form-group col-6">
        <label class="col-12 col-form-label" for="password">Password</label>
        <input type="password" placeholder="Password" id="password" class="form-control form-control-lg col-12" [formControl]="regForm.controls['password']" required>
        <div class="invalid-feedback">
          Please provide a password.
        </div>
      </div>
    </div>

    <div class="row justify-content-center">
      <div class="form-group col-6">
        <button type="submit" class="btn btn-outline-secondary btn-block col-12">Sign in</button>
      </div>
    </div>
  </form>
</div>

You could - and probably should, add the class="was-validated" programmatically, not hardcode it like i did.

If you have any trouble with this, feel free to comment my post - and i will update my answer.