Browse Source

數值驗證方法=>自訂欄位同步驗證方法

master
HarveyChou 2 years ago
parent
commit
28507f4648
  1. 15
      src/app/app.component.html
  2. 19
      src/app/app.component.ts
  3. 2
      src/app/app.module.ts
  4. 8
      src/app/validators/array-cannot-empty.validator.ts
  5. 23
      src/app/validators/decimal.validator.ts

15
src/app/app.component.html

@ -1,10 +1,7 @@
<div [formGroup]="form">
<div formArrayName="Tasks" *ngFor="let control of tasks.controls; let index = index">
<ng-container [formGroupName]="index">
<input type="text" placeholder="主旨" formControlName="Subject" />
<input type="text" placeholder="內容" formControlName="Content" />
</ng-container>
<div>
單價:<input type="text" [formControl]="formControl" />
<span *ngIf="formControl.hasError('decimal')">
單價應為 {{ formControl.errors?.decimal.digitLength }} 位整數位與
{{ formControl.errors?.decimal.scaleLength }} 位整數位的數值
</span>
</div>
<span *ngIf="tasks.hasError('cannotEmpty')">至少需要一筆工作事項</span>
</div>
<pre>{{ tasks.errors | json }}</pre>

19
src/app/app.component.ts

@ -1,23 +1,14 @@
import { Component } from '@angular/core';
import { FormArray, FormBuilder } from '@angular/forms';
import { arrayCannotEmpty } from './validators/array-cannot-empty.validator';
import { FormControl } from '@angular/forms';
import { decimalValidator } from './validators/decimal.validator';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
readonly form = this.fb.group({
tasks: this.fb.array([], {
validators: [arrayCannotEmpty]?
}),
readonly formControl = new FormControl(0, {
validators: [decimalValidator(2, 1)]
});
get tasks(): FormArray {
return this.form.get('tasks') as FormArray;
}
constructor(private fb: FormBuilder) {}
}

2
src/app/app.module.ts

@ -1,6 +1,6 @@
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

8
src/app/validators/array-cannot-empty.validator.ts

@ -1,8 +0,0 @@
import { FormArray, ValidationErrors } from '@angular/forms';
export function arrayCannotEmpty(formArray: FormArray): ValidationErrors | null {
if (formArray.length === 0) {
return { cannotEmpty: true };
}
return null;
}

23
src/app/validators/decimal.validator.ts

@ -0,0 +1,23 @@
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function decimalValidator(
digitLength: number,
scaleLength: number
): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (
control.value === undefined ||
control.value === null ||
control.value === ''
) {
return null;
}
const regular = new RegExp(
`^\\d{1,${digitLength}}(\\.\\d{0,${scaleLength}})?$`
);
return regular.test(control.value)
? null
: { decimal: { digitLength, scaleLength } };
};
}
Loading…
Cancel
Save