In my Angularjs application I need to have regular expression for two patterns for form validation with the following condition.
Pattern 1 :
The input box should accept alphanumeric with no space and it should also allow the user to use the characters like ~!@#$-_
any where in the string, except these characters non of the other characters should be allowed like (%, &, ^ etc)
. It should not allow leading/trailing whitespace also.
Examples :
ab@4_w : valid
sd!tye123 : valid
sd%tye123 : Invalid
sd*tye123 : Invalid
$scope.pattern1 = [\w~!@#\$-]+
Pattern 2: Should allow only alphanumeric with no space and no other characters including (_). It should not allow leading/trailing whitespace also.
Examples :
a4hgg5 : Valid
a4_6hy : Invalid
a@yb : invalid
$scope.pattern2 = [\w]+
$scope.pattern1
and $scope.pattern2
needs to be modified to meet my above requirements.
In both cases, add the
ng-trim="false"
attribute to theinput
element.The pattern you have is correct, but escaping characters that do not have to be escaped is not recommended, use:
Where
\w
matches[a-zA-Z0-9_]
.NOTE: if you pass the pattern as a string, do not add
^
and$
anchors, but double the backslashes:"[\\w~!@#$-]+"
.It is much easier:
^[a-zA-Z]+$
. Same comment about anchors as above applies.