The validation using regex is unsuccessful when the 6th character is entered

My attempt at validating URLs is encountering a problem. It consistently fails after the input reaches the 6th letter. Even when I type in "www.google.com," which is listed as a valid URL, it still fails to pass the validation.

For example:

w
ww
www
www.
www.g
www.go <-breaks here
www.goo <- continues to break

const validUrl = (value: string | null): string => {
    let item: string
    const regex = /^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})+(\.[a-zA-Z]{2,3})?((\/)?[a-z0-9-]{1,61}(\/)?){0,30}$/

    if (value === null || value === '') {
      return ''
    }

    if (value && typeof value === 'string' && !regex.test(value)) {
      for (item in urlStrings) {
        if (item.startsWith(value)) {
          return ''
        } else if (value.startsWith(item)) {
          return ''
        }
      }
    }
    return 'Invalid url'
  }

This is urlStrings:

export const urlStrings: { [key: string]: string } = {
  'www.costco.com': '',
  'www.walmart.com': '',
  'www.google.com': '',
  'www.facebook.com': '',
}

Answer №1

I recently tested out the regular expression you provided using https://regex101.com/ and found that it successfully matches www.go. However, it did not match www.g because all groups after the first \. require a minimum of two letters ({2,N} for some N).

It's possible that your code might be stopping after encountering the first failed match and not checking further input. Unfortunately, I was unable to replicate this issue by running your code.

I hope this information proves helpful to you.

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

transferring information between pages in nextjs

Currently in the process of developing a website, specifically working on a registration page for user sign-ups. My main challenge at the moment is validating email addresses without using Links. I need to redirect users to a new page where they can see if ...

Track when a user modifies a <select> dropdown list generated using the Jquery method ".html()"

Is it possible to detect a change in the value of a select list when that select list has been added using either the .html(htmlString) or .append(content[,content]) jQuery function? HTML CODE: <ul class="htmlClass"> <!-- Populated via JS --& ...

Storing jQuery output in a global variable can be achieved by assigning the result

Take a look at the Code snippet below - $(function() { $.fn.getPosition = function() { var results = $(this).position(); results.right = results.left + $(this).width(); results.bottom = results.top + $(this).height(); return results; } ...

What is the best way to choose an Animatedmodal that can showcase various demos while using just one ID?

I am currently customizing my website and utilizing the AnimatedModal.js framework. I have successfully displayed content in one modal, but encountered difficulty when attempting to create multiple modals as they all share the same ID. My question is, how ...

Validation for nested fields in objects using express-validator if the object exists

I am currently working on a Rest API Project using Express and NodeJs, with the addition of Express-Validator for request object validation. Within one of my services, the request body looks like this: { "name": "some value", " ...

What is the best way to send information from child components to their parent in React

I'm facing a scenario where I need to increase the parent value based on actions taken in the children components. Parent Component: getInitialState :function(){ return {counter:0} }, render(){ <CallChild value={this.state.counter}/> ...

Why is the result of this specific JavaScript code a string?

let x = 2, y = x = typeof y; console.log(x); // >> 'string' Could you explain why the value of x ends up being a string in this code snippet? ...

What is the best way to incorporate a button that, when clicked, reveals two separate images on the frontend?

describe food option heredescribe juice option hereHow can I create a button using HTML, CSS, JavaScript, and Bootstrap that displays different images for food and juices when clicked? For example, clicking on "food" will display 3 different food images, w ...

Ensure that the assistant stays beneath the cursor while moving it

I am currently working on creating a functionality similar to the 'Sortable Widget', but due to some constraints, I cannot use the premade widget. Instead, I am trying to replicate its features using draggable and droppable elements: $(".Element ...

The sample Ajax XML code provided by W3Schools is ineffective

While studying xml parsing in ajax on w3schools.com, I came across an example that functioned perfectly online. However, when I saved it to my desktop as abc.html and note.xml, the XML values weren't displaying. Even though the HTML elements were vis ...

Filtering data based on the model in React Native allows you to refine and organize

This code snippet represents a modal that contains two custom dropdown components, a text input, and a button. When the button is clicked, it filters data from an API. Currently, I am struggling to create a functional filter function despite multiple atte ...

Having difficulty fetching the object from mongodb for the parent function

I have a mongo collection object that I need to access outside of its function scope. This is my current approach: function getOldMessage(user) { //this is where i want to store the object var oldMsg = {}; messagedb.findOne({ "room": user.room }, functio ...

The AJAX response is shown just a single time

My code is designed to send an ajax request when a form is submitted, specifically a search module. It works perfectly the first time the form is submitted, highlighting the table when data is returned. However, I am only able to see the effect once, as th ...

Cookies are strangely absent from the ajax call to the web api - a puzzling issue indeed for Web Api users

Hello, here is the code I'm working with using Ajax: function GetCurrentUserId() { return $.ajax({ type: "GET", url: rootUrl + '/api/Common/CurrentDateAndUser', dataType: 'json', ...

The checkboxes seem to be malfunctioning following an ajax request

I've been attempting to utilize ajax to load data, but for some reason the checkboxes aren't functioning. Below is the HTML I'm trying to load via ajax: <div class="mt-checkbox-list" > <?php foreach($product_offerings as $row){ $c ...

Retrieve the content within a div tag

Hey there, I have a div set up as follows: <div>1+1</div> I'm looking to send this '1+1' value over to my javascript code and calculate it to get '2'. Appreciate any help in advance! ...

Using Python Webdriver to Execute JavaScript File and Passing Arguments to Functions

How can I execute a JavaScript function and pass arguments to it? value = driver.execute_script(open("path/file.js").read()) I have successfully executed the file, but I am unsure of how to pass arguments to the function within it. Any suggestions would ...

Issue with Dropdown Menu functionality while using multiple dropdown options

I am currently experimenting with dropdown menus from W3Schools and have encountered an issue when trying to implement two dropdown options. The code works fine for a single dropdown, but when I try to add a second one using GetElementsByClassName instead ...

An error has occurred in the callback function for the watcher "function () { return this._data.$$state }": "Error: [vuex] It is forbidden to modify the vuex store state outside of a mutation"

Here is a screenshot of the error I encountered in the console This is the method that I am using The issue seems to be happening in mounted I have also included MapState in the Computed section While my code is currently functional, I am puzzled by th ...

Leveraging spread syntax and styling for array string interpolation in JavaScript

Imagine I have an array such as [1,2,3] and my goal is to insert its values into a string format like: the values are (?, ?, ?) Can anyone suggest a simple solution for this? I am aware of the spread operator ...[1,2,3], and it's feasible to conver ...