5

How'd allow for an input using ng-pattern only: letters, numbers, dot, underscore and dash ( . _ -)?

Already tried the following ones

UPDATE:

$scope.validationPattern = '/^[a-zA-Z\d\-\_]+$/';

<input ng-model="model" type="text" ng-pattern="{{validationPattern}}" />
el.severo
  • 2,202
  • 6
  • 31
  • 62

3 Answers3

13

Judging by your requirements, you need to add a dot to the pattern:

$scope.regex = '^[a-zA-Z0-9._-]+$';

and add ng-trim="false" to the <input> tag so as to disallow leading/trailing spaces.

See this plunkr

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • one more question, if I'd like to add slash (`/`) too why `^[a-zA-Z0-9._-/]+$` does not works? – el.severo Aug 24 '16 at 13:37
  • Ok, just follow either strategy: 1) escape the hyphen and do not care what you add at the end of the character class or 2) always keep the hyphen at the end of the character class. If you escape in a string literal use double backslashes. – Wiktor Stribiżew Aug 24 '16 at 13:42
  • Thanks! in plunker it works but not in my project. I'm getting: `[$parse:lexerr] Lexer Error: Unexpected next character at columns 0-0 [^] in expression [^[a-zA-Z0-9._/-]+$]` , any idea? this is how the input looks like: `` – el.severo Aug 24 '16 at 14:21
  • Try `ng-pattern="/^[a-zA-Z0-9._\/-]+$/"` – Wiktor Stribiżew Aug 24 '16 at 17:52
4
[a-zA-Z0-9][A-Za-z0-9._-]*

this one works

jayanthCoder
  • 615
  • 1
  • 6
  • 13
2
/^[a-zA-Z0-9 ._-]+$/

This regex seems appropriate enough for you if it don't directly fit in ng-pattern make necessary adjustments, like.

in controller add

$scope.pattern = /^[a-zA-Z0-9 ._-]+$/;

now in html use ng-pattern="pattern"

Tested using this : http://www.regextester.com/

Accepts numbers, alphabets and three symbols(.-_)

Gandalf the White
  • 2,415
  • 2
  • 18
  • 39