Angularjs regular expression

190 Views Asked by At

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.

2

There are 2 best solutions below

2
On BEST ANSWER

It should not allow leading/trailing whitespace.

In both cases, add the ng-trim="false" attribute to the input element.

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).

The pattern you have is correct, but escaping characters that do not have to be escaped is not recommended, use:

^[\w~!@#$-]+$

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~!@#$-]+".

Should allow only alphanumeric with no space and no other characters including (_).

It is much easier: ^[a-zA-Z]+$. Same comment about anchors as above applies.

7
On

Try

^[\w~!@#\$-]+$

Explanation

  1. ^ Begin of string
  2. [\w~!@#\$-]+ Any number of the Characters you want, (note the need to escape $ like \$)
  3. $End of string

See in Action on Regex101. If you want empty strings to be valid, specify * instead of + for the quantifier. Also, when using \w you do not need to set the i flag, since it already covers both upper and lowercase letters.