Regular expression for ng-pattern to validate file paths

I have created a regex for file paths with specific conditions:

  • It must match the regex
    ^(\\\\[^\\]+\\[^\\]+|https?://[^/]+)
    , which means it can be a network path like \server\share (optionally followed by one or more "\folder"s), or an HTTP(S) URL
  • It should not contain any invalid characters in a path name, such as ", <, >, |

Is there a way to create a single regex to use in angular.js that satisfies these requirements?

Answer №1

Your current regular expression does not appear to be matching what you need. However, if it is working as intended, the following modification can be made to include a negation:

^(?!.*[ "<>|])(\\\\[^\\]+\\[^\\]+|https?://[^/]+)

Incorporating a negative lookahead allows us to check if any prohibited characters are present in the string before continuing with the rest of the pattern.

If I have correctly understood your requirements, you might consider this alternative approach:

^(?!.*[ "<>|])(\\\\|https?://).*$

This revised expression still excludes invalid characters identified by the negative lookahead while meeting the conditions for matching one or more path segments as well as http(s), and it offers simplicity.

It is worth noting that if your criteria call for 2 or more path segments or a trailing slash in the URL, the proposed solution may not suffice. Your original regex implies these additional specifications.

To account for multiple path segments or a trailing slash, a slightly modified version could be used:

^(?!.*[ "<>|])(\\\\[^\\]+\\.|https?://[^/]+/).*$

Furthermore, the request to match \server\share should actually read \\server\share. Therefore, all instances of \\\\ in the provided examples should be adjusted to \\ if this clarification applies.

Answer №2

Alright, let's start with the regular expression and then move on to the explanation:

(?<folderorurl>(?<folder>(\\[^\\\s",<>|]+)+)|(?<url>https?:\/\/[^\s]+))

The first condition is to match a folder name that should not contain any characters like ", <, >, or |, as well as no whitespaces. This part is denoted as:

[^\s,<>|] # using the caret to negate the character class

In addition, we want to allow for optional subfolders following the main folder name. To achieve this, we need to include a backslash in the character class:

[^\\\s,<>|] # including a backslash in the character class

We also aim to match one or more characters while making sure there is at least one match, which is indicated by the plus sign (+). Consider the example string:

\server\folder

Currently, only "server" is being matched, so we add a backslash to match "\server". Since file paths consist of a backslash followed by a folder name, we need to match this pattern multiple times (but at least once):

(\\[^\\\s",<>|]+)+

To improve readability, a named capturing group ((?<folder>)) is used:

(?<folder>(\\[^\\\s",<>|]+)+)

This will now match strings like \server or

\server\folder\subfolder\subfolder
and save them in a group labeled folder.

Next, let's move on to the URL part. A URL typically starts with http or https, followed by a colon, two forward slashes, and additional content:

https?:\/\/[^\s]+ # additional content must not have whitespaces

Following the same logic, this is stored in a named group called "url":

(?<folder>(\\[^\\\s",<>|]+)+)

Keep in mind that this regex may match invalid URLs (e.g.,

https://www.google.com.256357216423727...
). If this behavior is acceptable, you're good to go. Otherwise, you might want to refer to this question on SO.

Finally, let's combine these elements using an or, store them in another named group ("folderorurl"), and we're finished. Pretty simple, right?

(?<folderorurl>(?<folder>(\\[^\\\s",<>|]+)+)|(?<url>https?:\/\/[^\s]+))

Now, either a folder name or a URL can be found in the folderorurl group while still retaining the individual parts in url or folder. While I'm not familiar with angular.js, this regex should give you a good starting point. You can also check out this regex101 demo for a working example.

Answer №3

  • For validation, the input must adhere to the specified regex pattern:
    ^(\\\\[^\\]+\\[^\\]+|https?://[^/]+)
    . It should be either in the form of '\\server\share' (optionally followed by one or more "\folder"s) or a valid HTTP(S) URL
  • The input should not include any invalid characters such as ", <, >, |

To implement the second condition within your regex, ensure to incorporate the invalid characters into the negated character sets. For example, instead of using [^/], you would use [^/"<>|].

Below is a functional sample with a slightly modified regex pattern:

paths = [ '\\server\\share',
          '\\\\server\\share',
          '\\\\server\\share\\folder',
          'http://www.invalid.de',
          'https://example.com',
          '\\\\<server\\share',
          'https://"host.com',
          '\\\\server"\\share',
        ]
for (i in paths)
{
  document.body.appendChild(document.createTextNode(paths[i]+' '+
    /^\\(\\[^\\"<>|]+){2,}$|^https?:\/\/[^/"<>|]+$/.test(paths[i]))))
  document.body.appendChild(document.createElement('br'))
}

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

What is the best way to prevent Firefox from storing the data of a textarea in the local environment?

I have been developing a website locally, and I have noticed that there are numerous <textarea> elements present on the site. One issue I am facing is that whenever I reload the site, the content within the <textarea> remains the same. This pe ...

Create an Angular directive that highlights a div if any of its child inputs have focus

I've developed an Angular directive for a repetitive section containing form elements. My aim is to have the entire section highlighted whenever any input field inside it is focused. template.html <div class="col-md-12 employee-section"> <l ...

I'm curious if there is a method to indicate the specific destination within a separate file that the FS module in Node.js writes the data

Whenever I utilize the fs method fs.appendFileSync(example.json, jsonString, {'flags': 'a+'});, it successfully writes the data to the JSON file. However, the problem is that the data is not inserted into the array where I actually need ...

How to retrieve the present value from an array using AngularJS

Struggling to assign the current user from my list Here is my array after submitting the form [{"name":"Erich","surname":"Josh","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096c67497a7a276a6664">[email prot ...

Next.js is like Gatsby but with the power of GraphQL

I'm curious if it's possible to set up GraphQL in Next.js similar to how it's done in Gatsby, allowing me to query pages and retrieve data from them. Are there any plugins available for Next.js that work like Gatsby-file-source and gatsby-ma ...

Trigger the function upon displaying the modal

Within my Bootstrap project, I have set up a click event to trigger a modal as follows: $('#make_selects_modal').appendTo("body").modal('show'); My requirement is to run a function called pickClient when this modal is displayed. I att ...

Confirming the presence of an image using jQuery without enforcing it as mandatory

Situation: In my setup, I maintain a database that holds details about various items. Currently, I utilize a dynamic form to retrieve and exhibit the existing information on any item stored in the database. Any modifications made on the form are promptly ...

How to patiently wait for AngularJS to complete updating the DOM post AJAX requests in Selenium?

[Related philosophical debate about the benefits of simply sleeping it out on programmers.se] Angular doesn't always update the DOM completely in the AJAX completion event handler (especially with third-party directives), so many of the solutions fou ...

Exploring the functionality of the readline module using a simulated command-line

I am currently working on developing a unit test for a module that utilizes the "readline" functionality to interpret standard input and provide standard output. Module: #!/usr/bin/env node const args = process.argv.slice(2) var readline = require(' ...

Step-by-step guide to configuring preact-render-to-string with Express

Could someone guide me through setting up preact-render-to-string with express? Detailed instructions are here Installation for express can be found here I've gone through the provided links, but I'm unfamiliar with using node. I'm struggl ...

Bootstrapvalidator does not function properly with select2.js

My code is not validating the select field. What could be causing this issue? Can anyone provide a solution? Apologies for my poor English, and thank you in advance for your response. Here is my form: <form name="form_tambah" class="form_tambah"> ...

What is the method for attaching a keypress event to an HTML document?

Looking to add an interactive touch to my website by creating a "press any key" page. When a key is pressed, I want it to kick off animations that bring the page to life - like sliding elements in from different directions. Open to using jQuery or plain ...

What steps can I take to ensure my CSS selector for the element is functioning properly?

Here is an example of some code: <html> <head> <style> .test{ background-color: red; p { background-color: yellow; } } </style> </head> <body> <div class="test"> ...

Retrieve the property of an object from within an array

I am dealing with an array structure like this: const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; My goal is to extract and return the name of the object if its id matches a certain value. After exp ...

Obtain a URL using JavaScript's regular expressions

Is it possible to use JavaScript regex to fetch the first function parameter? For instance, when I click on a tag in this page element, how can I extract the inline link? Here's an example: <li><a href="#blog" data-rel="clos ...

Tips for customizing the WooCommerce product page

If you want to customize the layout of a WooCommerce product page, you can override the template by copying the WooCommerce template folder into your theme. You can find step-by-step instructions here. I am looking to change the layout of a WooCommerce pr ...

Identifying activity on a handheld device

I am currently working on a website and I have noticed that it doesn't work as well on mobile devices as it does on desktop. There are performance issues that need to be addressed. I've seen other websites redirecting users to a different page wh ...

Grabbing <object> HTML using jQuery

One example on my webpage is the presence of the following <object>: <object id="obj1" data="URL"></object> Could you please suggest a method to access this html object using jQuery? ...

Ensuring Compliance with GDPR through Cookie Consent Logic

Since the introduction of GDPR, I find myself in need of clarity on the steps to take both server-side and client-side to ensure compliance. Apologies for the plethora of questions. I currently have a first-party cookie that is used to store a session coo ...

Execute a JavaScript function when a form is submitted

Seeking to reacquaint myself with Javascript, encountering difficulties with this fundamental issue. https://jsfiddle.net/gfitzpatrick2/aw27toyv/3/ var name = document.getElementById("name"); function validate() { alert("Your name is " +name); } < ...