What could be causing the regular expression to fail in properly validating the website URL?

Here is the URL expression(regex) I am currently using to validate website URLs :

/(https?:\/\/)(www)?[A-Za-z0-9.\-@_~]+\.[A-Za-z]{2,}(:[0-9]{2,5})?(\/[A-Za-z0-9\/_\-.~?&=]*)*/

My implementation of angular JS code looks like this :

 <md-input-container class="md-block" style="margin-top:20px;">
        <label>Website</label> 
        <input ng-model="schoolDetails.website" name="website" ng-change="editField()" type="url" ng-pattern="/(https?:\/\/)(www)?[A-Za-z0-9.\-@_~]+\.[A-Za-z]{2,}(:[0-9]{2,5})?(\/[A-Za-z0-9\/_\-.~?&=]*)*/">
        <div ng-messages="schoolDetailsForm.website.$error">
           <div ng-message="pattern">Please enter a valid website</div>
       </div> 
</md-input-container>

If I provide a valid URL http://www.bharatividyapeeth.edu, it works properly. However, when entering an invalid URL such as http://www., the error message appears. But for an invalid URL like http://www.bharatividyapeeth, no error message shows up and it accepts it as a valid URL.

Could someone please help me correct my code to ensure proper validation of website URLs?

Thank you.

Answer №1

Are you looking for a more streamlined regex solution for your project? I've made some adjustments to your current regex pattern. While this should cover most instances of URLs, there may be certain scenarios where it doesn't provide accurate results.

/https?:\/\/(www\.)?(?!www\.)([A-Za-z0-9\-@_~]+\.)[A-Za-z]{2,}(:[0-9]{2,5})?(\.[A-Za-z0-9\/_\-~?&=]+)*/

Answer №2

It appears that this solution is accurate:

let url = 'https://www.universityofcambridge.co.uk'
let regex = /(http|https)(:\/\/)+?(w{3}(\.\w*\.))+(edu|co\.uk|com)/gi;

document.querySelector('pre').innerHTML = url.match(regex)[0];
<pre></pre>

Answer №3

If you're looking to check if a regex pattern will work for your needs, give this one a try:

(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})

With this expression, you can match URLs like:

http://www.bharatividyapeeth.edu
https://www.bharatividyapeeth.edu
www.bharatividyapeeth.edu

However, it won't match URLs such as:

http://www.bharatividyapeeth
https://www.bharatividyapeeth
www.bharatividyapeeth

To test the validity of this regex pattern, you can visit the following link:

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

Attempting to display a grid of product listings using a Websocket connection and an Express server

Recently, I attempted to create a live table of products using websockets for real-time updates. While I am new to this concept, I decided to upgrade an old project with websockets. Unfortunately, my attempts were unsuccessful, which is why I am seeking he ...

Unleashing the power of RollupJs: A guide to dynamically bundling modules and objects

Is there a way to dynamically bundle a module/object into my RollupJs output file? I have experimented with various options without success in achieving the desired result. Below is a brief sample project that demonstrates what I am trying to achieve. The ...

Accessing Django ManyToManyField via Ajax using its ID

Here are my models: class Topping(models.Model): name=models.CharField(max_length=24) class Pizza(models.Model): toppings=models.ManyToManyField(Topping) Now, onto the views: def get_pizza(request): if request.is_ajax(): pizza_list= ...

New messages are revealed as the chat box scrolls down

Whenever a user opens the chatbox or types a message, I want the scroll bar to automatically move down to show the most recent messages. I came across a solution that seems like it will do the trick: The issue is that despite implementing the provided cod ...

A versatile jQuery function for extracting values from a :input selector

Is there a universal method in jQuery to retrieve the value of any :input element? I pose this question because I have a webpage containing select and checkbox inputs, as seen in the code below: for (var i = 0; i < arguments.length; i++) { ...

What is the best method to clear data in a field following a change in selection in another field?

Currently, I am exploring the functionality of ejTimePicker from the reference site: In my project, I have implemented two select boxes, named textbox1 and textbox2, which store selected times. My goal is to reset the time in textbox2 whenever a different ...

Turn off the scrollbar without losing the ability to scroll

Struggling with disabling the HTML scrollbar while keeping the scrolling ability and preserving the scrollbar of a text area. Check out my code here I attempted to use this CSS: html {overflow:hidden;} Although it partially worked, I'm not complete ...

Angular JS: utilizing ng-repeat for precise iteration count

I am attempting to implement the following user interface functionality: https://i.sstatic.net/523Nr.png The task requires the user to choose three images. As per the requirements, an ng-repeat displays the selected images while leaving placeholders for ...

Exclude the CSS file from all elements except for the ones that are being appended to a specific div

Imagine you have a document with a CSS file that applies to all elements on the page. Is there a way to selectively remove or add styles from this file so they only affect a specific div and not the entire document? ...

Transition not influencing the scale property when activating a class

My modal is not scaling in and out properly when I toggle the 'active' class. It either fully scales out or scales in without any transition. Example: const openPopupButtons = document.querySelectorAll('[data-popup-target]'); const ...

How to isolate a function in React when mapping data

I am currently working on mapping data as a repeater in my React project. However, I am facing an issue with isolating the opening function, specifically with an accordion component. As I continue to learn React, I want to ensure that each accordion operat ...

Typescript indicates that an object may be 'undefined' when the value is an empty string

I'm new to Typescript and currently working on converting our application from React JSX to TS. If I'm misunderstanding the error, please let me know. I've encountered the error message Object is possibly 'undefined' related to a ...

Steps to take to save an HTML element as a PNG

Unique content: I am looking to convert a standard HTML element into an image on an HTML canvas for my website project. I am currently working on creating a website that involves displaying various elements on the screen. One of the key requirements is b ...

After updating React and Next.js to the latest versions, encountering a re-hydration error when refreshing a page? Looking for possible solutions to resolve this issue?

Encountered an unexpected Runtime Error Error: The hydration process failed because the initial UI does not align with the server-rendered content <div> <p> Gender : <span >{gender}</sp ...

Encountering the "Javascript must be enabled to run this" message when trying to retrieve data from an API

Express.js Setup const app = express(); app.use(express.static(path.join(__dirname, 'build'))); app.use(express.static(path.join(__dirname, 'doc'))); app.use(express.json({ limit: "10mb", type: "application/json" })) ...

What is the process for accessing a local .json file from a remote machine or folder?

I am currently working on a project that involves a .json file stored in my local folder. Along with the file, I have Javascript code in the same directory to access and read the values from the .json file. To open the file, this is the line of code I use: ...

Error encountered while attempting to serialize React Fragment: Symbol value cannot be converted to a string

Encountering an issue while attempting to render a React.Fragment: Error Message: Cannot convert a Symbol value to a string Snippet of the code being passed to a component: render{ const block = { type : 'menu', className: &ap ...

Conceal the elements of Widget Style by using jQuery to target the ul

My task involves creating a widget style using HTML's ul tag. <div class='tabs' style='width:50%'> <ul> <li id="basic-li"><a href='#basic_information'>Basic</a></li> <li id="mas ...

Creating a regex pattern that matches any text excluding quotation marks or consecutive hyphens

Could someone please assist me in creating a regular expression that allows for no quotes (single or double) but allows for single hyphens? For instance, "good", 'good', and good--looking should not be allowed (however, good-looking is acceptable ...

Issue: The object identified as #<Object> does not contain the 'toUpperCase' method

I am currently encountering the error Object #<Object> has no method 'toUpperCase' right before the POST request is initiated. Any assistance you can provide would be greatly appreciated! Thank you in advance. function ajaxeo(url, data, me ...