Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write an ng-pattern to disallow whitespaces and special characters

I am trying to get an angular ng-pattern to check that a username has no whitespaces or special characters. The following form return false if you enter whitespaces or special characters. However, it becomes true as soon as you enter a-z, A-z or 0-9. I have tried ng-pattern="/[^\s]+/" and \S and [^ ] but they make no difference.

<form name="myform">
  valid? {{ myform.$valid }}
  <input type="text" name="username" ng-model="username" ng-pattern="/[a-zA-Z0-9^ ]/" required/>
</form>

Here's the form in a plunk: http://plnkr.co/edit/6T78kyUgXYfNAwB4RHKQ?p=preview

like image 710
Craig Morgan Avatar asked Oct 17 '13 10:10

Craig Morgan


2 Answers

Try the following pattern:

/^[a-zA-Z0-9]*$/

This allows only alphanumeric characters.

like image 198
Ibrahim Najjar Avatar answered Oct 22 '22 10:10

Ibrahim Najjar


To surface the specific answer I was looking for, I already had the pattern suggested by Sniffer /^[a-zA-Z0-9]*$/, but angular still appeared to ignore leading/trailing whitespace. As Cristian mentions in the comments:

Angular will trim the input model, meaning that the validation doesn't trigger for spaces. You can add an ng-trim="false" to the input to fix this.

Note that Angular is trying to protect you by silently trimming whitespace by default. In my case, I want the user to be aware that the trailing whitespace is invalid.

like image 28
Johann Avatar answered Oct 22 '22 12:10

Johann