I am actually got a angular form and some input inside. The purpose is to upload files in a cloud. So, I got an input for a directory path which could contain some sub-directories. So I got a regex on my JS in a scope like this: $scope.regex = "^[^\/]\S+$";
this regex would accept any characters if its not a "/" at first character.
and here's my angular code:
<input name="directory" id="directory" type="text" class="form-control" ng-pattern="regex" ng-model="directoryName" placeholder="Enter a directory name"/>
<span class="error" ng-show="uploaderForm.directory.$error.pattern">directory path can't start by a "/"</span>
Normally, with this regex, this path should be success:
directory/subdirectories/filename...
and this one shouldn't:
/directory/subdirectories/filename...
But my problem is that when i'm writing something like : test/subtest/blablabla, I got the ng-show error...
Note that my input can also be a single char, like a.
Use
$scope.regex = "^[^/]\\S*$";
Or its equivalent regex literal notation:
$scope.regex = /^[^\/]\S*$/;
The first issue is solved with doubling the backslashes. To define a literal \ in JS string literal, you need to double it. See this thread.
The second problem is solved with replacing + (1 or more) with * (0 or more) quantifier. \S+ matches one or more non-whitespace chars, and \S* will match zero or more chars other than whitespace.
Details
^ - start of string[^\/] - any char other than /\S* - zero or more non-whitespace chars$ - end of string.Just in case you also want to allow an empty string, you may use a lookahead based regex:
$scope.regex = /^(?!\/)\S*$/;
Here, (?!\/) is a negative lookahead that will fail the match if the first char is /.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With