【发布时间】:2017-07-12 18:10:44
【问题描述】:
对于 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 类有什么问题吗?
谢谢!
【问题讨论】:
-
只能是因为
control.value.match(/^[a-z0-9]+$/i)总是匹配 -
那么正确的字母数字正则表达式是什么
-
在
if(...)之前添加console.log(control.value.match(/^[a-z0-9]+$/i));会得到什么? -
["b", index: 0, input: "b"] 用于字符 'b'
-
你可以试试
/^[a-z0-9]+$/i.test(control.value)而不是stackoverflow.com/questions/6603015/…
标签: angular typescript