iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0
Modern Web

Angular10 實作教學系列 第 26

NG10鐵人賽 - 26 - Template-Drive & Reacitve Forms 自訂驗證

  • 分享至 

  • xImage
  •  

Reactive Forms 自訂驗證

trim-required-validatorr.ts (自己手動建立檔案)

import { AbstractControl } from '@angular/forms';

export function TrimRequiredValidator(control: AbstractControl): { [key: string]: any } | null {
  const value = control.value;
  if (! value) { return { appTrimRequiredValidator: { valid: false }}; }
  const trimText = String(value) ? String(value).trim() : '';
  return (trimText.length === 0) ? { appTrimRequiredValidator: { valid: false } } : null;
}

app.component.html

<form (ngSubmit)="onSubmit()" [formGroup]="form">
  <div class="form-group">
    <label for="smallName">姓名 - appTrimRequiredValidator</label>
    <input id="smallName" class="form-control" formControlName="smallName">
    <div *ngIf="smallName.invalid && (smallName.dirty || smallName.touched)" class="alert alert-danger">
        <div *ngIf="smallName.errors.appTrimRequiredValidator">
            請輸入姓名(請勿輸入空白).
        </div>
     </div>
  </div>
</form>

app.component.ts

import { TrimRequiredValidator } from '../../validators/trim-required-validatorr';

form = new FormGroup({
    smallName:  new FormControl(this.defaultName, [
      TrimRequiredValidator,
    ]),
});

get smallName() { return this.form.get('smallName'); }

Template-Drive 自訂驗證

trim-required-validator.directive.ts (ng g directive 檔案名稱 [options])

import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl, AbstractControl } from '@angular/forms';
import { TrimRequiredValidator } from '../validators/trim-required-validatorr';

@Directive({
  selector: '[appTrimRequiredValidator]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => TrimRequiredValidatorDirective), multi: true }
  ]
})
export class TrimRequiredValidatorDirective implements Validator {
  validate(c: AbstractControl) {
    return TrimRequiredValidator(c);
  }
}

app.component.html

<div class="form-group col-md-6 text-left">
  <label for="b">移除空白必填</label>
  <input type="text" class="form-control" id="b" placeholder="b" name="b" [(ngModel)]="b"
  appTrimRequiredValidator #bNg="ngModel">
  <ng-container *ngIf="bNg.invalid && (bNg.dirty || bNg.touched)">
    <ng-container class="text-danger" *ngIf="bNg.errors['appTrimRequiredValidator']">
      <label class="text-danger">請輸入內容(不含空白)</label>
    </ng-container>
  </ng-container>
</div>

大神文章

https://blog.kevinyang.net/2017/03/10/angular-custom-validator/


上一篇
NG10鐵人賽 - 25 - ReactiveForm Validator 驗證
下一篇
NG10鐵人賽 - 27 - ng2-charts github 導讀
系列文
Angular10 實作教學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言