At the outset, there seems to be an issue with your regex due to excessive escaping symbols. In this case, you only need to escape the "
and \\
.
To tackle a "
within the ng-pattern
attribute, consider defining it as \x22
or "
:
var app = angular.module("app", []);
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<form name="form">
<p>Enter text to validate:</p>
<input type="text" ng-model="name" name="name" ng-pattern="/^[^\\\\./:*?"<>|][^\\\\/:*?\x22<>|]{0,254}$/" ng-trim="false" />
<div ng-show="form.name.$error.pattern">Text doesn't match with ng-pattern!</div>
</form>
</body>
</html>
You can also resolve the problem by creating a regex in the controller using a regular string literal, where you can employ '.."..'
or "..\"..."
. Subsequently, utilize the variable name within {{...}}
in the ng-pattern
attribute. Keep in mind that to match a literal \
, you will need to use 4 backslashes in the regex pattern.
var app = angular.module("app",[]);
app.controller("FormCtrl", function($scope) {
$scope.regex = "/^[^\\\\./:*?\"<>|][^\\\\/:*?\"<>|]{0,254}$/";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<form name="theForm" ng-controller="FormCtrl" novalidate>
<input type="text" name="filename" placholder="filename" ng-model="filename" ng-pattern="{{regex}}" required />
<div class="error"
ng-show="(theForm.filename.$dirty || attempted) && theForm.filename.$invalid">
<small class="error text-danger"
ng-show="theForm.filename.$error.required">
Please enter a file name.
</small>
<small class="error text-danger"
ng-show="theForm.filename.$error.pattern">
Please enter a valid file name.
</small>
</div>
</form>
</div>