Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 ngx-bootstrap form validation

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>
like image 338
Mike Glaz Avatar asked Nov 17 '17 10:11

Mike Glaz


People also ask

What is angular validation in Bootstrap 4?

Angular Validation - Bootstrap 4 & Material Design. Examples & tutorial. - Material Design for Bootstrap Angular Bootstrap validation is set of validators which can be used on various form inputs to provide valuable and actionable feedback to users. In order to turn on validation for a specific form control, add the mdbValidate directive to it.

What is mdbvalidate in angular bootstrap?

Angular Bootstrap validation is set of validators which can be used on various form inputs to provide valuable and actionable feedback to users. In order to turn on validation for a specific form control, add the mdbValidate directive to it. The mdb-error and mdb-success components allow us to display validation messages under the form element.

How to integrate Bootstrap with angular and ngmodel?

Add the Bootstrap CSS path in styles array inside the angular.json file. Now we have configured Angular and Bootstrap, run the command to open the app in the browser. To get started with Form control and NgModel Angular Forms service, we require to import FormsModule in app.module.ts file.

How does ng-bootstrap-form-validation work?

ng-bootstrap-form-validation works by using the form-group Bootstrap class on your divs as component selector, and projecting the content into a component which handles form validation feedback for you.


2 Answers

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.

like image 120
ChrisEenberg Avatar answered Sep 19 '22 16:09

ChrisEenberg


Props to @ChrisEenberg on this. If you want to have each field be validated as the user types, put the was-validated on the form-group <div class="form-group row" [ngClass]="{'was-validated': (categoryVar.touched || categoryVar.dirty) && !categoryVar.valid }">

like image 20
irhetoric Avatar answered Sep 20 '22 16:09

irhetoric