Ng-pattern With Regex Having Double Quotes Does Not Escape Correctly
I have a ng-pattern validation for a regex of ^[^\./:*\?\'<>\|]{1}[^\/:*\?\'<>\|]{0,254}$ which basically tests the invalid chars in filepath and teh limit. but when i
Solution 1:
First of all, your regex contains too many escaping symbols, while you only need to escape the "
here and \\
.
Then, to match a "
inside ng-pattern
attribute, you may define it as \x22
or "
:
var app = angular.module("app", []);
<htmlng-app="app"><head><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script></head><body><formname="form"><p>Enter text to validate:</p><inputtype="text"ng-model="name"name="name"ng-pattern="/^[^\\\\./:*?"<>|][^\\\\/:*?\x22<>|]{0,254}$/"ng-trim="false" /><divng-show="form.name.$error.pattern">Text doesn't match with ng-pattern!</div></form></body></html>
You may also solve the problem by defining a regex in the controller with a regular string literal where you may use '.."..'
or "..\"..."
, and then use the variable name inside {{...}}
in the ng-pattern
attribute. Note that to match a literal \
you need to use 4 backslashes in the regex pattern.
var app = angular.module("app",[]);
app.controller("FormCtrl", function($scope) {
$scope.regex = "/^[^\\\\./:*?\"<>|][^\\\\/:*?\"<>|]{0,254}$/";
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="app"><formname="theForm"ng-controller="FormCtrl"novalidate><inputtype="text"name="filename"placholder="filename"ng-model="filename"ng-pattern="{{regex}}"required /><divclass="error"ng-show="(theForm.filename.$dirty || attempted) && theForm.filename.$invalid"><smallclass="error text-danger"ng-show="theForm.filename.$error.required">
Please enter a file name.
</small><smallclass="error text-danger"ng-show="theForm.filename.$error.pattern">
Please enter a valid file name.
</small></div></form></div>
Solution 2:
I was trying to exclude ' and " in a ng-pattern which is similar to the problem above. I found a way to embed ' or " directly without having to use a scope variable:
<input type="text" ng-pattern="/^[^"']+$/" />
Solution 3:
You can use \"
to escape "
.
Post a Comment for "Ng-pattern With Regex Having Double Quotes Does Not Escape Correctly"