angular 指令中的无效正则表达式错误
Invalid regular expression error in angular directive
条件:
内容只能包含以下集合中的字符:
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
0 1 2 3 4 5 6 7 8 9
/ - ? : ( ) 。 , ' +
• 内容不得以“/”开头
• 内容不得包含“//”
export function directDebitValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const directDebitID = nameRe.test(control.value);
return directDebitID ? { 'directDebit': { value: control.value } } : null;
};
}
@Directive({
selector: '[directDebit]',
providers: [{ provide: NG_VALIDATORS, useExisting: DirectDebitValidatorDirective, multi: true }]
})
export class DirectDebitValidatorDirective {
validate(control: AbstractControl): { [key: string]: any } | null {
return control.value ? directDebitValidator(new RegExp("^(? !.* [\/]{2})[a-zA-Z0-9-?:().,'+]+([a-zA-Z0-9\/-?:().,'+])*$"))(control)
: null;
}
}
有几个问题:
- 前瞻定义中不能有空格
[/-?]
创建范围,-
必须转义或放在字符class的start/end处。
- 您可以在构造函数符号中使用未转义的
/
,因为那里没有使用定界符。
所以,您可以使用
directDebitValidator(new RegExp("^(?!.*/{2})[a-zA-Z0-9?:().,'+-][a-zA-Z0-9/?:().,'+-]*$"))
或者,使用正则表达式文字表示法:
directDebitValidator(/^(?!.*\/{2})[a-zA-Z0-9?:().,'+-][a-zA-Z0-9\/?:().,'+-]*$/)
参见regex demo。
条件:
内容只能包含以下集合中的字符:
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 / - ? : ( ) 。 , ' +
• 内容不得以“/”开头 • 内容不得包含“//”
export function directDebitValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const directDebitID = nameRe.test(control.value);
return directDebitID ? { 'directDebit': { value: control.value } } : null;
};
}
@Directive({
selector: '[directDebit]',
providers: [{ provide: NG_VALIDATORS, useExisting: DirectDebitValidatorDirective, multi: true }]
})
export class DirectDebitValidatorDirective {
validate(control: AbstractControl): { [key: string]: any } | null {
return control.value ? directDebitValidator(new RegExp("^(? !.* [\/]{2})[a-zA-Z0-9-?:().,'+]+([a-zA-Z0-9\/-?:().,'+])*$"))(control)
: null;
}
}
有几个问题:
- 前瞻定义中不能有空格
[/-?]
创建范围,-
必须转义或放在字符class的start/end处。- 您可以在构造函数符号中使用未转义的
/
,因为那里没有使用定界符。
所以,您可以使用
directDebitValidator(new RegExp("^(?!.*/{2})[a-zA-Z0-9?:().,'+-][a-zA-Z0-9/?:().,'+-]*$"))
或者,使用正则表达式文字表示法:
directDebitValidator(/^(?!.*\/{2})[a-zA-Z0-9?:().,'+-][a-zA-Z0-9\/?:().,'+-]*$/)
参见regex demo。