德语编号验证

时间:2017-09-19 11:37:32

标签: angular validation

如何验证文本框中的德语值输入。

我查看Validators文档,但它不包含任何数字验证器。

德国号码的样本:

  • 0
  • 12,5
  • 100.000
  • 100.000,25

1 个答案:

答案 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>