The issue arises when trying to escape double quotes within a regex pattern using ng-pattern

My ng-pattern validation includes a regex pattern ^[^\./:*\?\"<>\|]{1}[^\/:*\?\"<>\|]{0,254}$ to prevent invalid characters in file paths and set a limit. However, when I specify the ng-pattern as:

 ng-pattern = "^[^\\\./:\*\?\"<>\|]{1}[^\\/:\*\?\"<>\|]{0,254}$"

The ng-pattern displays the regex incorrectly. Can anyone offer guidance on how to implement this correctly?

Answer №1

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 &quot;:

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="/^[^\\\\./:*?&quot;<>|][^\\\\/:*?\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>

Answer №2

I encountered a dilemma when attempting to avoid using single and double quotes within an ng-pattern, similar to the issue described earlier. However, I discovered a method to incorporate single or double quotes directly without relying on a variable:


<input type="text" ng-pattern="/^[^&#34&#39]+$/" />

Answer №3

To escape the character ", simply use \&quot;.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue.js axios method returns undefined; v-for directive fails to iterate - Issue on Wordpress site

Using a shortcode, I have integrated Vue.js into a Wordpress page. pl2010_vue_init_directory = pl2010_vue_init_directory || (function(ctx) { new Vue( { el: '#'+ctx.el, data: { errorMsg: "", successMsg: "", show ...

There was a unexpected JSON response from the Django backend that triggered an alert in the Chrome

Trying to send back a JSON file to the Chrome extension for user display. The query is reaching the server without issues, and the fetched URL does return the JSON file when accessed directly. However, the Chrome extension displays an "undefined" message i ...

What could be causing Highchart to return the error message "Typeerror: undefined variable byte"?

My current project involves creating a graph using highchart and updating values every second. I am also working on displaying data in Mb, Kb, and Gb format on the graph by developing a function to convert byte values. Here is a snippet of my code: // hi ...

Executing Angular testing with the command $scope.$apply

What is the reason behind having to use $scope.$apply() in a test case for asynchronous processes to complete? Assume there is a service angular.service("a",function($q){ return { getValue: function(){ return $q.resolve(someObj) ...

Set a unique class for several elements depending on a given condition

Is there a way to assign a color class based on the element's value without looping through all elements? Check out my jsfiddle HTML <div> <ul> <li class="MyScore">90</li> <li class="MyScore"> ...

Adjust the size of the Div and its content to fit the dimensions of

Currently, I have a div containing elements that are aligned perfectly. However, I need to scale this div to fit the viewport size. Using CSS scale is not an option as it does not support pixel values. https://i.stack.imgur.com/uThqx.png I am looking to ...

Uncovering a particular property within an array with the help of EJS

I am still learning about ejs and javascript. I have an ejs file where I want to display a list of array objects with unique properties. My goal is to iterate through the array's length, check if a specific property matches a string, and then display ...

Integrate CKEditor with elFinder to allow for direct file uploads

I am utilizing the elFinder Laravel package for file management with CKEditor. I have followed all the steps and everything is working fine except for one issue. When I click on the image button in CKEditor to select or upload an image, after selecting an ...

javascript unable to change the text in the textarea

My application takes user input from a textarea element, calls an API to retrieve values, and then compares those values against a list of known "badwords." If a match is found, the word is highlighted in red to indicate it is spelled incorrectly. The pro ...

When attempting to navigate to a new route with a query, I encounter the error message "NavigationDuplicated: Avoided redundant navigation to current location."

I'm facing an issue with my navigation header setup. It includes a search bar that redirects users to the home view with the search query as a parameter. Here's the code snippet for reference: <template lang="html"> <div cl ...

JavaScript now assigns a value of null in place of undefined

When working with JavaScript, it's important to understand that undefined can be reassigned. Because of this, it is recommended to create a self-executing function to ensure that undefined remains undefined. Are there any other values that are loosely ...

Assign the ngClick event handler to the capturing phase

Can the ngClick event handler be configured to work in the capturing phase, as discussed in this informative article? I am interested in stopping events from propagating down to child elements and then back up again when a specific condition is met for t ...

Populating the array by calculating the average values

I'm encountering an issue in my JavaScript code. I have a situation where I must fill gaps in an array with the averages of the surrounding values. Let me provide an example: Array: 1, 2, 3, ,4, 5 In this case, I would need to fill the gap with the ...

Ways to retrieve text files prior to the webpage loading (synchronously)

I have a simple task at hand that I really want to accomplish - loading some glsl fragment shaders from the disk or server, and then initializing a WebGL web page. Web programming is not my forte; I usually prefer working on shaders and OpenGL in C++. If i ...

Utilize JavaScript to send login information to a website

I have a specific task in mind: creating a script that will automatically fill in certain data on an HTML website. To illustrate, let's imagine the site is the StackOverflow login page and I want to input my username and password. For the username fi ...

Tips for efficiently transmitting and fetching form data within an angular/node system

I am currently developing an app using the mean.js boilerplate. My angular view contains a form that needs to submit some formData: <form name="form" ng-submit="postUpdate()"> <div class="form-group"> <f ...

Using a regular expression to replace occurrences of a string in Objective-C

Can someone help me figure out how to use a regex expression to split my string that contains HTML code? NSString* regex = @"<.*?>"; NSString* html = @"<span class="test">Test1</span><span class="test">Test2</span><span cl ...

Using Express.js with Pug.js, dynamically render the page with new content following a fetch POST request

I have a collection of article previews sourced from a database and rendered on the webpage using a Pug.js mixin. each article in articles +articlePreview(article.title, article.text, article.imgSrc) To enhance the user experience, I want to implem ...

Utilize React Native to continuously fetch and display data from this API

[React-Native] Seeking assistance on looping through JSON API for conditional rendering. As a beginner, I would greatly appreciate your guidance. Thank you. Find my code here: https://drive.google.com/file/d/0B3x6OW2-ZXs6SGgxWmtFTFRHV00/view Check out th ...

Saving information from JSON data obtained through the Google People API

My server is connected to the Google People API to receive contact information, and the data object I receive has a specific structure: { connections: [ { resourceName: 'people/c3904925882068251400', etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLD ...