答案 0 :(得分:0)
我刚写了自己的验证器:
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';
@Directive({
selector: '[germannumber]',
providers: [{ provide: NG_VALIDATORS, useExisting: GermannumberValidatorDirective, multi: true }]
})
export class GermannumberValidatorDirective implements Validator {
validate(control: AbstractControl): { [key: string]: any } {
let valid = true;
if (control.value) {
let numberString = control.value as string;
// remvoe thousend dots, replace the comma
numberString = numberString.replace('.', '').replace(',', '.')
let number = parseFloat(numberString);
valid = number.toString() === control.value;
}
// the value is accessibale under
// [ELEMENTNAME].errors,germannumber
return valid ? null : { 'germannumber': true }
}
}
用法:
<div class="form-group">
<label for="germannumber">germannumber</label>
<input id="germannumber"
name="germannumber"
class="form-control"
germannumber
[(ngModel)]="germannumber"
#name="ngModel">
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.errors.germannumber">
Nummer entspricht nicht dem Detuschen nummernformat!
</div>
{{name.errors | json}}
</div>
</div>