Browse Source

自訂表單驗證

master
HarveyChou 2 years ago
parent
commit
2339adb55f
  1. 19
      src/app/app.component.html
  2. 3
      src/app/app.module.ts
  3. 44
      src/app/decimal-validator.directive.ts

19
src/app/app.component.html

@ -1,14 +1,19 @@
<form #form="ngForm">
<div>
密碼<input
type="password"
name="password"
#password="ngModel"
單價<input
type="text"
name="price"
#price="ngModel"
ngModel
pattern="[a-zA-Z]*"
appDecimalValidator
[digitLength]="2"
[scaleLength]="1"
/>
<ng-container *ngIf="password.touched">
<span *ngIf="password.hasError('pattern')">密碼只接受英文字母</span>
<ng-container *ngIf="price.touched">
<span *ngIf="price.hasError('decimal')">
單價應為 {{ price.errors?.decimal.digitLength }} 位整數位與
{{ price.errors?.decimal.scaleLength }} 位整數位的數值
</span>
</ng-container>
</div>
</form>

3
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 { }

44
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,
},
};
}
}
Loading…
Cancel
Save