JavaScript regular expressions only recognize certain characters

When submitting a form, I need to validate a field and ensure that only specific characters are allowed. The permitted characters include:

a-z A-Z 0-9 % . " ' & - @ # $ * / + = [ ] !

I attempted to use the following regex for validation:

var regex = new RegExp(/[a-zA-Z0-9%\. "'&@#\$\*\/\+=\[\]\!-]+/); 

After testing it on , it appeared to match the pattern correctly. However, during form submission validation, it did not reject input containing characters such as (, ), or ?. For instance, entering (afasdf) in the form field resulted in a true match.

Any suggestions on how to resolve this issue?

<input type="text" class="field">
<p>
    <button>Validate</button>
</p>
var field = document.querySelector('.field');
var button = document.querySelector('button');
var regex = new RegExp(/[a-zA-Z0-9%\. "'&@#\$\*\/\+=\[\]\!-]+/, 'g');

button.addEventListener('click', function() {
    console.log(regex.test(field.value));
}, false);

Jsbin link https://jsbin.com/forupos/edit?html,js,console,output.

Answer №1

The function will return true for input (afasdf), even though it actually matches afasdf. To ensure accurate matching, you should consider using ^n and n$ anchors.

var regex = new RegExp(/^[a-zA-Z0-9%\. "'&@#\$\*\/\+=\[\]\!-]+$/); 

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

Guide to selecting an element with a combination of text and a random number using Selenium with JavaScript

<a id="Message4217" class="btn-sm btn-danger Message" data-id="4217"><span class="icon-adjustment icon-trash"></span> Delete</a> The objective is to remove a message base ...

Upon initial login, React fails to retrieve notes

I developed a note-taking React app using the MERN stack with React Router DOM v6. When I initially visit the website, I am directed to the login page as intended. However, upon logging in, the page refreshes but does not redirect to the home page. This is ...

Steps for transferring JSON data from the controller to JavaScript

Within my cluster Table, there is a column called description which stores cluster coordinates in JSON format. I want to draw multiple cluster polygons on Google Maps using these coordinates. id | description ...

Issue with Counting Digg Button Clicks

I can't figure out why the digg button counter isn't working. I followed the instructions but... The website in question is: . I implemented the code exactly as explained here: But the counter remains at 0. Has anyone encountered a similar iss ...

Having issues with unchecking checkboxes in ReactJS

I created a task management app and I thought of improving it by displaying all completed tasks when the "Show completed tasks" box is checked. https://i.stack.imgur.com/RkXsw.png The issue I'm facing is that while checking "Show completed tasks ...

Javascript issue: opening mail client causes page to lose focus

Looking for a solution! I'm dealing with an iPad app that runs html5 pages... one specific page requires an email to be sent which triggers the Mail program using this code var mailLink = 'mailto:' + recipientEmail +'?subject=PDFs ...

Utilizing a combination of a `for` loop and `setInterval

I've been encountering an issue for the past 3-4 hours and have sought solutions in various places like here, here, here, etc... However, I am unable to get it to work in my specific case: var timer_slideshow = {}; var that, that_boss, has_auto, el ...

Developing Modules in NodeJS using Constructors or Object Literals

I am currently developing a nodejs application that needs to communicate with various network resources, such as cache services and databases. To achieve this functionality, I have created a module imported through the require statement, which allows the a ...

When attempting to swap out ":customimage:" with an image in a React.js HTML view, the result displayed is [object Object]

I have created a function below: WordColonsToImage(comment) { var newcomment = comment.replace(/:wave:\s*/g, <img src={wavinghand} />) return newcomment } Here is an example: WordColonsToImage("Hi! :wave:") whi ...

One of the great features of Next.js is its ability to easily change

At the moment, my dynamic path is configured to display events by their ID [id].js localhost:3000/event/1 But I would like it to be structured as follows: localhost:3000/city/date/title. All of this information is available in the events database, but I&a ...

Mastering div manipulation with jQuery: A step-by-step guide

I have three divs with the classes "col-md-2," "col-md-8," and "col-md-2." What I want is that when a button in the "col-md-8" div is clicked, both of the other divs should be hidden and the "col-md-8" div should expand to occupy the full width of "col-md ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

Issues with Mega Menu functionality preventing items from being clickable and links from properly navigating

Recently, I encountered a strange issue related to the integration of a mega menu found at . Unfortunately, despite integrating the mega menu, the Category and sub category links seem unresponsive - they are not directing me to the desired links. I suspec ...

Using the KnockOut js script tag does not result in proper application of data binding

Being new to knockout js, I found that the official documentation lacked a complete html file example. This led me to write my own script tags, which initially resulted in unexpected behavior of my html markups. Strangely enough, simply rearranging the pos ...

Exploring the JSON data in Javascript using Ajax

Completely new to Javascript, I am just trying to grasp the basics of the language. Currently, I have a JSON request set up with the following code: function request(){ $.ajax({ dataType: "jsonp", type: 'GET', url: "getWebsite", ...

Retry an Ajax request immediately after a timeout without having to wait for the full

I am attempting to resend an AJAX request every 5 seconds if there is an issue, but when I simulate an offline connection with Chrome, the AJAX request doesn't wait 5 seconds between each attempt and keeps getting called continuously. What could be c ...

"Effortlessly transform a JSON string into a JSON Object with JavaScript - here's how

When I serialize my object using the ASP.net JavaScriptSerializer class and return it to the client side, how can I deserialize the string in JavaScript? ...

Is it possible to integrate external search functionality with Vuetify's data table component

I am currently working with the v-data-table component from Vuetify, which comes with a default filter bar in its properties. This table retrieves data from a local JSON file. The issue arises when I have another external component, a search bar created u ...

Applying Tailwind styles to dynamically inserted child nodes within a parent div

Currently, I am in the process of transitioning my website stacktips.com from using Bootstrap to Tailwind CSS. While initially, it seemed like a simple task and I was able to replace all the static HTML with tailwind classes successfully. However, now I ha ...

Discovering whether a link has been clicked on in a Gmail email can be done by following these steps

I am currently creating an email for a marketing campaign. In this email, there will be a button for users to "save the date" of the upcoming event. I would like to implement a feature that can detect if the email was opened in Gmail after the button is cl ...