Google+

Friday, January 24, 2020

How to create a Custom Validator for a Select control using Angular 7

In this article we review how to create a Custom Validator using Angular 7,  in an Angular Application that includes a Template Driven Form , custom validator that allows to ignore a default "Select a city" value  , looking like this :











You can copy-paste all pieces of source code from this Tutorial, or elsewhere you can download the entire Angular code from the following URL:
https://github.com/CarmelSchvartzman/ANGULAR/blob/master/CUSTOM_VALIDATORS/SELECT_VALIDATOR


How to create a Custom Validator  for a Select control using Angular7


//////////////////////  CUSTOM VALIDATOR :


import { Directive } from '@angular/core';
import { Validator, AbstractControl, ValidationErrors, NG_VALIDATORS } from '@angular/forms';

@Directive({
  selector: '[appRequiredValidator]',
  providers: [{ provide: NG_VALIDATORS, useExisting: RequiredValidatorDirective, multi: true }]
})
export class RequiredValidatorDirective implements Validator {
  validate(control: AbstractControl): ValidationErrors {
    return control.value === '-1' ? { noValueChosen: true } : null;

  }
}



//////////////////// HTML VIEW :


      <div class="form-group" [class.has-error]='city.errors?.noValueChosen'  [class.has-success]='city.valid'>
        <label class='control-label' for="city">
          City
        </label>
        <select #city='ngModel'   appRequiredValidator   class="form-control" name="city" id="city" [(ngModel)]='friend.city'>
          <option  style='color:rgb(201, 149, 149)' value='-1'>Select a City</option>
          <option *ngFor='let c of cities' [value]="c.id">{{c.name}}</option>
        </select>
        <span class='help-block' *ngIf='city.errors?.noValueChosen'>Please select a city</span>
      </div>


/////////////////////  COMPONENT :

 cities: City[] =
    [{ id: 1, name: 'Athens' }, { id: 2, name: 'Volos' }, { id: 3, name: 'Thesaloniki' },
    { id: 4, name: 'Santorini' }, { id: 5, name: 'Corfu' }];


/////////////////////  MODULE :

import { RequiredValidatorDirective } from './shared/required-validator.directive';

@NgModule({
  declarations: [
    RequiredValidatorDirective
  ],
............

The results :






And finally, if the DEFAULT value is chosen again :






That's All!!! 
Enjoy Angular.....

      by Carmel Schvartzman

כתב: כרמל שוורצמן

No comments:

Post a Comment