I have a custom validator in my Angular 7 application. I need it to only accept certain characters, however, it is still accepting characters that are not included in my condition.
My custom validator:
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 };
}
The first character cannot be an empty space, which is working fine. After that, the only characters it should accept are the following:
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
The problem is, I can enter characters like * ) ( + : ; = > < ? and it will consider those valid. How can I modify this validator to make sure those are excluded?
Use this character class. Yours is permitting a range from #
to @
, rather than just those three individual characters. That's why the bad ones are slipping through:
[-a-zA-Z0-9,.#@%&']