修改此正则表达式,使其只接受在此条件下给出的字符

Modify this regex expression so that it only accepts characters given with this condition

我的 Angular 7 应用程序中有一个自定义验证器。我需要它只接受某些字符,但是,它仍然接受不包含在我的条件中的字符。

我的自定义验证器:

  static addressFormat(control: AbstractControl): { [key: string]: boolean } {
    const isValidAddress = (/^([a-zA-Z0-9,.#-@%&'])([a-zA-Z0-9,.#-@%&'\s/]?)+$/).test(control.value);
    return isValidAddress ? null : { addressFormat: true };
  }

第一个字符不能为空space,这没问题。 在那之后,它应该接受的唯一字符如下:

Numbers 0 to 9

Uppercase letters A-Z (you will see the expression accepts lowercase, but ive taken care of that with making each form control value uppercase inside the input tag)

period .

apostrophe '

hyphen -

comma ,

hashtag #

at sign @

percentage %

ampersand &

slash /

spaces 

问题是,我可以输入像 * ) ( + : ; => < ? 这样的字符,它会认为这些字符有效。我如何修改此验证器以确保排除这些字符?

使用这个字符class。您的允许范围从 #@,而不仅仅是这三个单独的字符。这就是为什么不好的人会溜走的原因:

 [-a-zA-Z0-9,.#@%&']