From 2339adb55fa10136d5ff3be7e2750ee86977bddd Mon Sep 17 00:00:00 2001 From: HarveyChou Date: Mon, 7 Nov 2022 18:27:29 +0800 Subject: [PATCH] =?UTF-8?q?=E8=87=AA=E8=A8=82=E8=A1=A8=E5=96=AE=E9=A9=97?= =?UTF-8?q?=E8=AD=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/app.component.html | 19 +++++++---- src/app/app.module.ts | 3 +- src/app/decimal-validator.directive.ts | 44 ++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 8 deletions(-) create mode 100644 src/app/decimal-validator.directive.ts diff --git a/src/app/app.component.html b/src/app/app.component.html index 33c1523..a6cbb9f 100644 --- a/src/app/app.component.html +++ b/src/app/app.component.html @@ -1,14 +1,19 @@
- 密碼: - - 密碼只接受英文字母 + + + 單價應為 {{ price.errors?.decimal.digitLength }} 位整數位與 + {{ price.errors?.decimal.scaleLength }} 位整數位的數值 +
diff --git a/src/app/app.module.ts b/src/app/app.module.ts index 93c6719..e399534 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -3,10 +3,11 @@ import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; +import { DecimalValidatorDirective } from './decimal-validator.directive'; @NgModule({ imports: [ BrowserModule, FormsModule ], - declarations: [ AppComponent ], + declarations: [ AppComponent, DecimalValidatorDirective ], bootstrap: [ AppComponent ] }) export class AppModule { } diff --git a/src/app/decimal-validator.directive.ts b/src/app/decimal-validator.directive.ts new file mode 100644 index 0000000..c1e0bc7 --- /dev/null +++ b/src/app/decimal-validator.directive.ts @@ -0,0 +1,44 @@ +import { Directive, Input } from '@angular/core'; +import { + AbstractControl, + NG_VALIDATORS, + ValidationErrors, + Validator, +} from '@angular/forms'; + +@Directive({ + selector: '[appDecimalValidator]', + providers: [ + { + provide: NG_VALIDATORS, + useExisting: DecimalValidatorDirective, + multi: true, + }, + ], +}) +export class DecimalValidatorDirective implements Validator { + @Input() digitLength!: number; + @Input() scaleLength!: number; + + validate(control: AbstractControl): ValidationErrors | null { + if ( + control.value === undefined || + control.value === null || + control.value === '' + ) { + return null; + } + + const regular = new RegExp( + `^\\d{1,${this.digitLength}}(\\.\\d{0,${this.scaleLength}})?$` + ); + return regular.test(control.value) + ? null + : { + decimal: { + digitLength: this.digitLength, + scaleLength: this.scaleLength, + }, + }; + } +}