Reputation: 2866
I'm trying write a validator for checking if there's whitespace and/or special characters, but I'm not sure on how to proceed.
so far, this is what I have:
const isValid = !/(^\s!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?|!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?\s$)/g.test(control.value)
but it doesn't seem to work. I'm sure I'm doing something wrong with my regex but I have no idea what.
Upvotes: 0
Views: 915
Reputation:
To check that beginning and end does not have special characters you need to use regex character class with the characters between [
and ]
. The ^
check the beginning and the $
check the end. The pipe |
for or ensures the beginning and end is checked.
const isValid = !/^[\b\^\s\!\@\#\$\%\^\&\*\(\)\_\+\-\=\[\]\{\}\;\'\:\"\b\|\,\.\<\>\/\?]|[\b\^\s\!\@\#\$\%\^\&\*\(\)\_\+\-\=\[\]\{\}\;\'\:\"\b\|\,\.\<\>\/\?]$/.test(control.value)
Escaping non-special characters in strings and regular expressions doesn’t have any effects on result, so it is more safe (bugfree) to have backslash on all the characters. It makes code more easy to understand. It does not get slower to execute.
To escape a backslach you do \b
, not \\
You do not need the g
flag that is for continued search.
No need to backspace on these:
!
@
#
$
%
^
&
*
(
)
,
.
?
"
:
{
}
|
<
>
Upvotes: 0
Reputation: 73
Can you use the below regex instead and check:
/^[\s@!*$%&^#$()\-+_={}[\]/?><.,'";:`~|].*[\s@!*$%&^#$()\-+_={}[\]/?><.,'";:`~|]$/gm
There are problems with the regex you are using like characters not escaped properly and not grouped properly.
It's easy to build regex using regex builder where you can understand the meaning and usage of every character while building itself.
Upvotes: 1
Reputation: 2424
Right now you are trying to match a string with all the special characters at the beginning or at the end, in the same order.
You need to use brackets to tell the regex that you are looking for one of these characters, not necessary all.
(^[\s!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]|[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?\s]$)
Upvotes: 1