JavaScript fails to effectively validate URLs

I have implemented the following validation for URLs:

jQuery.validator.addMethod("urlValidatorJS", function (value, element) {
    var regExp = (/^HTTP|HTTP|http(s)?:\/\/(www\.)?[A-Za-z0-9]+([\-\.]{1}[A-Za-z0-9]+)*\.[A-Za-z]{2,40}(:[0-9]{1,40})?(\/.*)?$/);
    return this.optional(element) || regExp.test(value);
}, "The URL format is incorrect");

However, I noticed that the validation is allowing invalid URLs such as: http://www.example.com/ %20here.html (URL with space).

Could anyone suggest how to fix this issue in the validation?

Answer №1

(\/.*)?

You mentioned that the final part of the URL may consist of a forward slash followed by multiple instances of any character.

If you wish to exclude spaces, provide more detailed information than simply using ..

Answer №2

Initially, there is a validation module available in jQuery that you could utilize.

Here is the regex to detect the URLs specified (remember the i flag at the end!):

/^(https?:\/\/)(?:[A-Za-z0-9]+([\-\.][A-Za-z0-9]+)*\.)+[A-Za-z]{2,40}(:[1-9][0-9]{0,4})?(\/\S*)?/i

You overlooked the possibility of other addresses like http://some.other.example.com. Additionally, your use of the identifier . was too broad. I substituted it with \S for any non-whitespace character. There were also some unnecessary identifiers such as {1} and the additional HTTP in the initial part of your regex.

You can explore your regex and test it on various strings using websites like regex101. It breaks down each section of your regex for easier debugging.

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

Retrieve the webpage content (including any iframes) using a Firefox plugin

Hello there! I am currently working on retrieving data from a webpage that is updated using Javascript. Initially, I attempted to create a Java program to periodically fetch this page from the server, but the information was being updated too slowly. The ...

Easy steps to launch Excel application with an HTML button using a web browser

How can I create a button on an HTML page that will launch an Excel application when clicked by the user? <button class="btn btn-primary" onclick="window.open('excelApplication.url','_blank')">Launch Excel</button> ...

The functionality of JSON.stringify does not take into account object properties

Check out the example on jsfiddle at http://jsfiddle.net/frigon/H6ssq/ I have encountered an issue where JSON.stringify is ignoring certain fields. Is there a way to make JSON.stringify include them in the parsing? In the provided jsfiddle code... <s ...

express-validator: bypass additional validation in a user-defined validator

Utilizing the express-validator package for validating my request data. As per the documentation, we need to declare them in this manner: app.use(expressValidator({ customValidators: { isArray: function(value) { return Array.isArray(value); ...

Tips for retrieving the ID of a dynamic page

In my Higher Order Component (HOC), I have set up a function that redirects the user to the login page if there is no token. My goal is to store the URL that the user intended to visit before being redirected and then push them back to that page. However, ...

Centering navigation using HTML5

I've been struggling a bit trying to build a website, particularly with centering my <nav> tag. Despite reading numerous suggestions like using CSS properties such as margin: 0 auto; or text-align: center, nothing seems to be working for me. Si ...

Adjust the jQuery.ScrollTo plugin to smoothly scroll an element to the middle of the page both vertically and horizontally, or towards the center as much as possible

Visit this link for more information Have you noticed that when scrolling to an element positioned to the left of your current scroll position, only half of the element is visible? It would be ideal if the entire element could be visible and even centere ...

How can you merge webSDK with jQuery within a Vue Component?

I am currently working on incorporating the webSDK found at into our Vue application. My goal is to load jquery only within a single component. Below is the code I have written, however, when I click the button, it does not seem to function as expected. ...

Encountering a problem while verifying pattern using regular expressions

I'm facing an issue when manually checking if my inputs match the specified patterns. Below is the function I am using for this check: if (!$element.attr("pattern")) return true; let pattern = $element.attr("pattern"); le ...

Achieving a transparent background in WebGLRender: A guide

I've been experimenting with placing objects in front of CSS3DObjects using the THREE.NoBlending hack. However, in the latest revisions (tested on r65 and r66), I only see the black plane without the CSS3DObject. Here is a small example I created: in ...

The $http service factory in Angular is causing a duplication of calls

After creating an angular factory that utilizes the $http service, I encountered a problem where the HTTP request is being made twice when checking the network tab in the browser. Factory: app.factory('myService', function ($http, $q) { var de ...

Why does TypeScript keep throwing the "No inputs were found in the config file" error at me?

Why am I receiving the No inputs were found in config file error from TypeScript? I have set up my tsconfig.json in VS Code, but the error occurs when I try to build it. The terminal displays: error TS18003: No inputs were found in config file '/Use ...

Execute a function upon pressing the enter key

Currently, I am working on coding a webpage with a form that includes one field where users input a set of numbers. After typing in the numbers, they should then press a button labeled 'Run' to execute the code. However, the issue arises when use ...

Is there a way to begin using the :nth-child() selector from the last element instead of the first?

$('button').click(function(){ $('ul').find('li:nth-child(2)').css('color', '#f00') }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> < ...

Resolving the Persistence Problem of Navigation Bar Fading In and Out

I've been struggling for hours trying different methods to achieve the desired outcome, but unfortunately, none of them have worked as expected. My goal is simple: I want the fixedbar to fade in when the scroll position exceeds the position of the ph ...

Aligning divs, prevent duplicate HTML within multiple divs

Currently, I am attempting to troubleshoot a jsfiddle issue. The main problem lies in my desire for the first two divs (with class="fbox") to be aligned next to each other on the same level. Furthermore, I am looking to enable dragging the image into the ...

Replace Ajax Success Function

Looking to customize the behavior of the jQuery ajax function by handling a default action upon successful execution, while still running the callback function specified in the options parameter. Essentially, I need to filter out specific tags from the res ...

How can I show an item repeatedly with each button click in ReactJS?

Currently, I have a setup where I can display a checkbox and its label upon clicking a button. However, the limitation is that only one checkbox can be displayed at a time. Is there a way to modify this so that I can show multiple checkboxes simultaneous ...

Execute the eslint loader within the node_modules of a specific directory that is npm linked and has not been compiled

One of the benefits of using webpack 4 is the ability to run eslint across the entire project folder with a specific configuration. { enforce: 'pre', test: /\.js|ts$/, exclude: /node_modules/, loader: 'eslin ...

Using Angular expressions, you can dynamically add strings to HTML based on conditions

I currently have the following piece of code: <div>{{animalType}}</div> This outputs dog. Is there a way to conditionally add an 's' if the value of animalType is anything other than dog? I attempted the following, but it did not ...