Angular Bootstrap inputs validation

Validation is very important, which is why we have prepared a number of validators at MDB.


Reactive Forms - Angular default validators

minLength Validator

minLength validation attribute is set to 3.



<form [formGroup]="validatingForm">
    <div class="md-form">
        <input mdbInputDirective type="text" id="form2" class="form-control" data-error="wrong text" data-success="right text" formControlName="minlength">
        <label for="form2">minLength validator</label>
    </div>
</form>
	

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

@Component({
    selector: 'validators-component-example',
    templateUrl: 'validators-example.html',
})
export class ValidatorsComponent {

    validatingForm: FormGroup;
    constructor(private fb: FormBuilder) {
        this.validatingForm = fb.group({
            'minlength': [null, Validators.required, Validators.minLength(3)],
        });
    }
}
  

maxLength Validator

maxLength validation attribute is set to 5.



<form [formGroup]="validatingForm">
    <div class="md-form">
        <input mdbInputDirective type="text" id="form3" class="form-control" data-error="wrong text" data-success="right text" formControlName="maxlength">
        <label for="form3">maxLength validator</label>
    </div>
</form>
	

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

@Component({
selector: 'validators-component-example',
templateUrl: 'validators-example.html',
})

export class ValidatorsComponent {

    validatingForm: FormGroup;
    constructor(private fb: FormBuilder) {
    this.validatingForm = fb.group({
        'maxlength': [null, Validators.maxLength(5)],
        });
    }
}
  

Min value Validator

Min value is set to 10.



<form [formGroup]="validatingForm">
    <div class="md-form">
        <input mdbInputDirective type="number" id="form4" class="form-control" data-error="wrong number" data-success="right number" formControlName="min">
        <label for="form4">min value validator</label>
    </div>
</form>
	

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

@Component({
    selector: 'validators-component-example',
    templateUrl: 'validators-example.html',
})

export class ValidatorsComponent {

    validatingForm: FormGroup;
    constructor(private fb: FormBuilder) {
    this.validatingForm = fb.group({
        'min': [null, Validators.min(10)],
        });
    }
}
  

Max value Validator

Max value is set to 10.



<form [formGroup]="validatingForm">
    <div class="md-form">
        <input mdbInputDirective type="number" id="form5" class="form-control" data-error="wrong number" data-success="right number" formControlName="max">
        <label for="form5">max value validator</label>
    </div>
</form>
	

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

@Component({
    selector: 'validators-component-example',
    templateUrl: 'validators-example.html',
})

export class ValidatorsComponent {

    validatingForm: FormGroup;
    constructor(private fb: FormBuilder) {
    this.validatingForm = fb.group({
        'max': [null, Validators.max(10)],
        });
    }
}
  

Email Validator



<form [formGroup]="validatingForm">
    <div class="md-form">
        <input mdbInputDirective type="email" id="form6" class="form-control" data-error="wrong email" data-success="right email" formControlName="email">
            <label for="form6">max value validator</label>
    </div>
</form>
	

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

@Component({
    selector: 'validators-component-example',
    templateUrl: 'validators-example.html',
})

export class ValidatorsComponent {

    validatingForm: FormGroup;
    constructor(private fb: FormBuilder) {
    this.validatingForm = fb.group({
        'email': [null, Validators.email],
        });
    }
}
  

Pattern Validator

Pattern Validator should contains RegEx. With it, pattern is able to validate through regular expressions. In this example, RegEx allows to put only english letters into input.



<form [formGroup]="validatingForm">
    <div class="md-form">
        <input mdbInputDirective type="text" id="form7" class="form-control" data-error="wrong text" data-success="right text" formControlName="pattern">
        <label for="form7">only letters (pattern) validator</label>
    </div>
</form>
	

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

@Component({
    selector: 'validators-component-example',
    templateUrl: 'validators-example.html',
})

export class ValidatorsComponent {

    validatingForm: FormGroup;
    constructor(private fb: FormBuilder) {
    this.validatingForm = fb.group({
        'pattern': [null, Validators.pattern(/A-Za-z/)],
        });
    }
}
  

Required Validator



<form [formGroup]="validatingForm">
    <div class="md-form">
        <input mdbInputDirective type="text" id="form1" class="form-control" data-error="Something went wrong..." data-success="Everything is okay!" formControlName="required">
        <label for="form1">Required validator</label>
    </div>
</form>
	

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

@Component({
    selector: 'validators-component-example',
    templateUrl: 'validators-example.html',
})
export class ValidatorsComponent {

    validatingForm: FormGroup;
    constructor(private fb: FormBuilder) {
    this.validatingForm = fb.group({
        'required': [null, Validators.required],
    });
    }
}
  


Resetting a validation status



<!-- Login form -->
<form [formGroup]="loginForm">
  <p class="h5 text-center mb-4">Sign in</p>

  <div class="md-form">
    <i class="fa fa-envelope prefix grey-text"></i>
    <input type="text" formControlName="defaultFormEmail" id="defaultForm-email" class="form-control" mdbInputDirective>
    <label for="defaultForm-email">Your email</label>
  </div>

  <div class="md-form">
    <i class="fa fa-lock prefix grey-text"></i>
    <input type="password" formControlName="defaultFormPass" id="defaultForm-pass" class="form-control" mdbInputDirective>
    <label for="defaultForm-pass">Your password</label>
  </div>

  <div class="text-center">
    <input type="submit" mdbBtn color="default" class="waves-light" mdbWavesEffect value="Login" (click)="submit(loginForm)">
  </div>
</form>
<!-- Login form -->
	

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

@Component({
    selector: 'validation-reset',
    templateUrl: './validation-reset.component.html',
    styleUrls: ['./validation-reset.component.scss'],
})
export class ValidationResetComponent implements OnInit {
    loginForm: FormGroup;
    constructor(private fb: FormBuilder, private _el: ElementRef, private _r: Renderer2) {
        this.loginForm = fb.group({
            defaultFormEmail: ['', Validators.required],
            defaultFormPass: ['', [Validators.required, Validators.minLength(8)]]
        });
    }
    submit(form: any) {
        const success = this._el.nativeElement.querySelectorAll('.counter-success');
        const danger = this._el.nativeElement.querySelectorAll('.counter-danger');
        const textSuccess = this._el.nativeElement.querySelectorAll('.text-success');
        const textDanger = this._el.nativeElement.querySelectorAll('.text-danger');
        success.forEach((element: any) => {
            this._r.removeClass(element, 'counter-success');
        });
        danger.forEach((element: any) => {
            this._r.removeClass(element, 'counter-danger');
        });
        textSuccess.forEach((element: any) => {
            this._r.setStyle(element, 'visibility', 'hidden');
        });
        textDanger.forEach((element: any) => {
            this._r.setStyle(element, 'visibility', 'hidden');
        });
        form.reset();
    }
}
  

Custom validation messages

data-error, data-success provides space to enter your's custom error or success message.

Use can now use [errorMessage] and [successMessage] inputs to add custom messages as strings or to pass variables defined in your typescript file. Those inputs will only work when data-error and data-success attributes are not available.

If you do not want to use the validation, use [mdbValidate]="false" on the input element, which should not display the validation status. Use [validateSuccess]="false" or [validateError]="false" to disable only one type of message.


<form>
    <div class="md-form">
      <i class="fa fa-envelope prefix"></i>
      <input mdbInputDirective data-error="wrong email" [formControl]="emailFormEx" data-success="valid email" minLength="8" maxLength="25"
        type="email" class="form-control" id="form9" name="email" mdbInputDirective>
      <label for="form9">Type your e-mail</label>
    </div>
  
    <div class="md-form">
      <i class="fa fa-lock prefix"></i>
      <input mdbInputDirective data-error="wrong password" [formControl]="passwordFormEx" data-success="valid password" minLength="10"
        maxLength="25" type="password" class="form-control" id="form10" name="password">
      <label for="form10">Type your password</label>
    </div>

    <div class="md-form">
        <input mdbInputDirective data-error="wrong password" [mdbValidate]="false" [formControl]="noValidation" data-success="valid password" type="text" class="form-control" id="form11" name="password">
        <label for="form11">Turn off validation</label>
      </div>

      <div class="md-form">
        <input mdbInputDirective data-error="wrong password" [validateSuccess]="false" [formControl]="noSuccessValidation" data-success="valid password" type="text" class="form-control" id="form12" name="password">
        <label for="form12">Turn off success validation</label>
      </div>

      <div class="md-form">
        <input mdbInputDirective data-error="wrong password" [validateError]="false" [formControl]="noErrorValidation" data-success="valid password" type="text" class="form-control" id="form13" name="password">
        <label for="form13">Turn off error validation</label>
      </div>

      <div class="md-form">
        <input mdbInputDirective [errorMessage]="errorMessage" [successMessage]="'Custom success message'" [formControl]="customMessages" type="text" class="form-control" id="form14" name="password">
        <label for="form14">Custom validation messages</label>
      </div>
  </form>
    

import { FormControl, Validators } from '@angular/forms';
import { Component } from '@angular/core';

@Component({
  selector: 'error-success-message',
  templateUrl: './error-success-message.component.html',
  styleUrls: ['./error-success-message.component.scss'],
})
export class ErrorSuccessMessageComponent {
  emailFormEx: FormControl;
  passwordFormEx: FormControl;
  noValidation: FormControl;
  noSuccessValidation: FormControl;
  noErrorValidation: FormControl;
  customMessages: FormControl;
  errorMessage = 'Custom error message';

  constructor() {
    this.emailFormEx = new FormControl('', Validators.email);
    this.passwordFormEx = new FormControl('', Validators.required);
    this.noValidation = new FormControl('', Validators.required);
    this.noSuccessValidation = new FormControl('', Validators.required);
    this.noErrorValidation = new FormControl('', Validators.required);
    this.customMessages = new FormControl('', Validators.required);
  }
}
    

API Reference:

In order to speed up your application, you can choose to import only the modules you actually need, instead of importing the entire MDB Angular library. Remember that importing the entire library, and immediately afterwards a specific module, is bad practice, and can cause application errors.

API Reference for MDB Angular Validation:
// MDB Angular Pro
import { InputsModule, WavesModule, ButtonsModule } from 'ng-uikit-pro-standard'
// MDB Angular Free
import { InputsModule, WavesModule, ButtonsModule } from 'angular-bootstrap-md'
// Angular Forms Modules
import { FormsModule, ReactiveFormsModule } from '@angular/forms'