我正在尝试在角度素材中使用 md-error 来验证来自客户端的用户输入。
所以在我的情况下,我正在尝试验证接受两种模式的输入字段。
正则表达式1:接受前9个字符作为数字然后接受第10个 字符为 x 或 X 或 v 或 V
正则表达式2:接受12个字符作为数字
所以我在我的打字稿文件中实现了这个,如下面的
samplefile.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
const NIC_REGEX_OLD = /[0-9]{9}[x|X|v|V]$/; // Regular Expression 1
const NIC_REGEX_NEW = /[0-9]{12}$/; // Regular Expression 2
@Component({
selector: 'sample-form',
templateUrl: `sample.html`,
styleUrls: ['sample.css']
})
export class SampleComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
sampleFormControl = new FormControl('', [
Validators.pattern(NIC_REGEX_OLD)
]);
}
这是上述字段的HTML内容
<div class="sample">
<md-form-field>
<input mdInput required [formControl]="sampleFormControl" maxlength="12">
<md-error *ngIf="sampleFormControl.hasError('pattern')">
Please enter the valid sample input
</md-error>
</md-form-field>
</div>
对于单个正则表达式(单一模式)这工作正常,但由于我需要验证两个模式,我尝试按照typescript文件中的方法
方法1:
sampleFormControl = new FormControl('', [
Validators.pattern(NIC_REGEX_OLD || NIC_REGEX_NEW)
]);
方法2:
sampleFormControl = new FormControl('', [
Validators.pattern(NIC_REGEX_OLD),
Validators.pattern(NIC_REGEX_NEW)
]);
但以上都没有正常工作,是否可以使用md-error验证多个模式?请评论
答案 0 :(得分:3)
你所尝试的是模式(AND
条件)的组合应该在一起满足,然后只有该字段才有效。但实际上您需要满足RegEx
之一,这就是为什么要考虑创建一个自定义validator
,它会使用OR
运算符手动测试RegEx。
<强>代码强>
function validateInput(c: FormControl) {
let NIC_REGEX_OLD = /[0-9]{9}[x|X|v|V]$/; // Regular Expression 1
let NIC_REGEX_NEW = /[0-9]{12}$/; // Regular Expression 2
return (NIC_REGEX_OLD.test(c.value) || NIC_REGEX_NEW.test(c.value)) ? null : {
validateInput: {
valid: false
}
};
}
//Usage
sampleFormControl = new FormControl('', [
validateInput
]);
答案 1 :(得分:0)
使用 |
在单个字符串中编写两个正则表达式,然后使用单个 Validators.pattern ("your expression")
。
这里可以是 Validators.pattern("/[0-9]{9}[x|X|v|V]$/|/[0-9]{12}$/")
。
注意这里我使用了一个 or 两个正则表达式。