Error in Javascript: Character class range is not in order

My regular expression (regex) seems to be incorrect:

var domain = "google\.com\.br";
var reEmail = new RegExp("^([A-Za-z0-9_\-\.])+\@" + domain + "$");

I am trying to use this regex to validate an email address. Here is an example:

reEmail.test("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b2824253f2a283f0b2c24242c272e65282426652939">[email protected]</a>");

However, I keep encountering the following error message:

The range specified in the character class is out of order

Answer №1

When you create the RegExp using a String, the characters _\-\. get interpreted as _-., resulting in an invalid range. (This creates a range from _ to ., which is incorrect)

To fix this issue, you must double escape it:

new RegExp("^([A-Za-z0-9_\\-\\.])+@" + domain + "$");

This way, the \\ becomes a \ in the String and correctly escapes the - in the RegExp.

UPDATE:

It's always helpful to log the result when creating a RegExp from a String so you can verify if it's correct:

For example, logging your part of the RegExp would show:

console.log("^([A-Za-z0-9_\-\.])+\@");

Which results in:

^([A-Za-z0-9_-.])+@

Answer №2

RegEx operates on strings, not numbers, which is why you can't use /[1-16]/ for a 2 digit number range like 1 to 16 - this will result in an error as it is not a valid range.

To properly define the range, you should use:

/([1-9]|1[0-6])/;

It's important to note that when using the above expression, you must also specify that the value should be less than 17 to avoid unintended matches with numbers containing 6 like 26 or 36.

Alternatively, you can use the following approach:

/1|2|3...|15|16/

In the second method, you need to replace the ellipsis (...) with |4|5 and so forth.

For more information on REGEX ranges, visit

If needed, consider utilizing a FOR LOOP to filter or test your data instead.

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

issue retrieving data from live website created with next.js

Hello, I've exhausted all possible avenues to identify the cause of the error occurring on my live website built with NEXTJS. I have observed that this error only occurs when I reload the website. It's worth noting that I can successfully login ...

The `Target closed` error in Playwright Library is triggered solely by the closing of either the `context` or `browser`

The code snippet below showcases a Node.js script that leverages the Playwright Library for browser automation (not Playwright Test) to extract data from a local website and display the results in the terminal. The challenge arises when the script encounte ...

Enable Intellisense for my custom ES6 JavaScript modules in VS Code

Using VS Code Intellisense can greatly enhance productivity when working with internal project files, providing helpful autocompletion features and utilizing written JSDoc comments. However, my current projects involve custom JavaScript libraries stored i ...

Assign a specific attribute to a checkbox, gather all selected attributes, and transmit them using jQuery

I have a system generated table with approximately 800 rows that needs checkboxes added for users to select specific rows for more information. I can add a checkbox column to the entire table at once, but I don't want to manually assign values to each ...

Is there a way to invoke a jQuery function from an ASP.NET environment?

I'm having trouble figuring out how to properly invoke a jQuery function. ScriptManager.RegisterStartupScript(GetType(), "Javascript", "countdown(); ", true); The issue is that it attempts to call the method inline, preventing it from executing the ...

Tips for updating the selected date format in a Material Table component using React

In the context of using a material table in React, the columns set up are as follows: columns={[ { title: 'Name', field: 'name', type: 'string', }, ...

Experience the power of Kendo UI Date Picker combined with AngularJS. When the datepicker is initialized, it starts

Check out my code snippet below: When the datepicker loads initially, it appears empty. However, if you remove ng-model from the directive template, the datepicker displays its initial value correctly. Yet, changing the selected date does not mark the fo ...

What steps can you take to address Git conflicts within the yarn.lock file?

When numerous branches in a Git project make changes to dependencies and use Yarn, conflicts may arise in the yarn.lock file. Instead of deleting and recreating the yarn.lock file, which could lead to unintended package upgrades, what is the most efficie ...

Execute the function only in response to changes in the data

I have a scenario where I am making an ajax call every 3 seconds to keep my app updated with rapidly changing information. However, the expensive function that I run inside the $.done() callback is causing my app to slow down. I want to optimize this proce ...

JavaScript code to generate a random color for the box shadow effect

Recently, I developed a function that generates random divs containing circles. The function randomly selects a border color for each circle, and this feature is functioning correctly. To enhance the appearance, I decided to add a box shadow to the circl ...

I encountered a ReferenceError stating that the variable "req" is not defined when I try to

I am currently developing a login application using React.js and Node.js (Express, JWT), but I am facing an issue when trying to export my function. I keep receiving the error ReferenceError: req is not defined, even though I have defined req. How can I re ...

Steps to implement a text border in Raphael.js

I have a website dedicated to creating customized football jersey designs. I'm utilizing Raphael.js for customization, and I am looking for a way to add an outline to text using Raphael. My research led me to the suggestion of using the stroke proper ...

What is the most efficient method for conditionally rendering components in React?

I'm currently in a dilemma about how to render a component based on a certain condition in React. Which way is considered the best practice? Your expertise would greatly assist me as I navigate through this decision-making process. First approach: co ...

Execute a middleware prior to running the Nest Js ServeStaticModule command

Is there a way to execute middleware before Nest JS serves my React application through the ServeStatic Module? I've attempted using both a Nest middleware and Global middleware, but they only seem to work for static routes such as '/'. mai ...

Can PHP retrieve data when the form submit function is overridden with AJAX?

I have customized the .submit function of a form on this webpage. It is being loaded inside the #mainContent in an "index.php" and I want the Submit button to only replace this #mainContent. My goal is to retrieve data from this form and send it to a .php ...

How do I use props to enable and conceal elements like lists, buttons, and images?

Check out this unique component: <ReusedHeader H1headerGray="text here... " H2headerRed="text2 here ! " pheader="p1" getStarted="button text1" hrefab="button url 1" whatWeDo="button text ...

State of the Browser - JavaScript/jQuery

Looking for a method to identify when my browser is loading and display a loading icon. Is this approach appropriate, or should I follow a more common practice to achieve the same goal? Edit: This feature will be implemented on one of my websites during ...

Node Express application experiences issues with Handlebars rendering additional empty objects from JSON arrays

Currently, I am attempting to retrieve data from a REST API call and display it as a list using Handlebars, which functions as my view engine in a Node Express App. Below is the route I am using: router.get('api/projects', function(req, res){ ...

What is the best way to dynamically search and retrieve data from a JSON object in Angular?

I am facing a challenge with my Angular (v. 1.6.3) app where I have fetched a JSON object containing stock price data. The structure of the JSON object only allows querying using brackets, with each key being a string that may include spaces, parentheses, ...

Oops! An error occurred when attempting to log in with an unidentified authentication method called "local"

After following a tutorial to build my project, I encountered an issue with the login functionality. While the signup process works fine, attempting to log in a registered user using postman results in the error: Error: Unknown authentication strategy "loc ...