字母数字验证无效

时间:2017-02-22 15:33:55

标签: angular typescript

对于Angular 2应用程序,我编写了一个自定义验证器TypeScript类,如下所示,

import { FormControl } from '@angular/forms';

export class AlphaNumericValidator {
    static invalidAlphaNumeric(control: FormControl): { [key: string]: boolean } {
        if (control.value.length && !control.value.match(/^[a-z0-9]+$/i)) {
            return { invalidAlphaNumeric: true };
        }
        return null;
    }
}

我将此验证器应用于模型驱动表单

'name': [this.exercise.name, [Validators.required, AlphaNumericValidator.invalidAlphaNumeric]],

这是HTML,

<label *ngIf="exerciseForm.controls.name.hasError('invalidAlphaNumeric') && (exerciseForm.controls.name.touched || submitted)" class="alert alert-danger validation-message">Name must be alphanumeric</label>

我注意到每当我在输入中输入一个字符时,上面的TypeScript类代码都被调用,但每次返回Null时都会显示。

typeScript类有什么问题吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

使用

!/^[a-z0-9]+$/i.test(control.value)

获取布尔结果

相关问题