【问题标题】:alpha numeric validation is not working字母数字验证不起作用
【发布时间】: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


【解决方案1】:

使用

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

得到布尔结果

【讨论】:

  • 我试过这个,但现在即使是有效的字母数字值,错误消息总是会出现
  • 无法复制。这在浏览器控制台中运行良好,例如 !/^[a-z0-9]+$/i.test('abc') (false) 或 !/^[a-z0-9]+$/i.test('ab.) (true)
  • 会不会是一个字符是数字,一个字符是非数字?
  • 你能说得更具体些吗?您究竟想允许/禁止什么?
  • 对于输入“abc”应该是真的,对于“234”也是真的,但是对于“7Alph”应该是假的。输入内容必须至少包含一个字符和一个数字
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
  • 2016-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多