When using the test() method in JavaScript with regular expressions, it may return true even if not all characters match, even when using

When attempting input validation in a textarea, I encountered the following issue:

const re= /^[0-9A-Za-zÀ-ÿ\s\’\'\:\.\-\,\!\[\]\(\)\@\&\?]+?$/im;
re.test(control.value)

During the first test:

+

The result was false as expected.

However, during the second test:

+
1234

The test() returned true, even though it should have still been false due to the presence of an invalid character and the use of ^...$.

If you can shed light on this issue, it would be greatly appreciated.

Thanks!

Answer №1

The main issue lies with the m flag - it is used to match the start and end of a line, not the entire string. As a result, even if only one line adheres to the regex pattern, the whole string will be considered valid.

To rectify this, you should include newline characters in your character set (if they are permitted) and remove the m flag. This adjustment ensures that the ^ and $ symbols will strictly match the beginning and end of the string:

const re= /^[0-9A-Za-zÀ-ÿ\s\’\'\:\.\-\,\!\[\]\(\)\@\&\?\n]+?$/i;
const validate = str => re.test(str);
document.querySelector('textarea').onchange = function() {
  console.log(re.test(this.value));
}
<textarea>
</textarea>

Answer №2

Feel free to take a look at the example here. In this case, the 'm' flag has been added to signify that '^ and $ matches start and end of line'

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

Obtaining template attributes in CKEditor: A guide

I have been working with the template plugin in CKEditor to load predefined templates. Each template is defined as follows: templates: [ { title: "Quickclick 1", image: "template1.png", description: "Quickclick 1 template", html_et: "& ...

How can one effectively develop a component library that is compatible with both React and Preact?

I'm currently in the midst of a project that involves both React and Preact. I've come across a situation where I need to utilize the same component for both React and Preact. Would it be wise to package the component into an npm library? What a ...

Enable the entire button to be clickable without the need for JavaScript by utilizing a Bootstrap 5 button

Is there a way to make a button redirect when clicking anywhere on it, not just the text inside? Here is the button code utilizing Bootstrap 5: <button class="btn btn-rounded btn-primary" type="button">Placeholder Text</button& ...

Tips for altering objects within an array

I am dealing with an array of objects that looks like this: const items = [ {name: 'Sam', amount: '455gbjsdbf394545', role: 'admin'}, {name: 'Jane', amount: 'iwhru84252nkjnsf', role: 'user'}, ...

Transmitting client-side Javascript data to backend server using Express

I am trying to fetch data from my frontend using the DOM and send it to the backend through Express but I'm unsure of how to proceed. I have used a POST method to console.log the data, but now I need help retrieving it in my Express backend. (The cons ...

The Bootstrap datepicker functions properly when used in plain HTML, but encounters issues when implemented within the .html()

Using HTML: <input class="m-ctrl-medium date-picker" size="16" type="text" id='lateETD1' name="dateRecv" value=""/> Not working with script: var ETD = $("#ETD"); ETD.html("<input class='m-ctrl-medium date-picker' id='la ...

Retrieve the value of the element and combine them together (The parseFloat function may not work as expected

The following code is what I am currently working with: var num1=$("#num1").val(); //the num1 value is 12.60 //html code for this number <input id="num1" value="12.60" /> num1=parseFloat(num1).toFixed(2); var num2=$("#num2").text(); //the num2 valu ...

What's going on with the background color? It doesn't seem

I have incorporated Bootstrap into my html code and I am attempting to modify the background color of a div when the screen resolution changes from large to medium or small. Even though I have added a class, the change does not reflect when adjusting the ...

How can I make a method in VueJS wait to execute until after rendering?

There is a button that triggers the parse method. parse: function() { this.json.data = getDataFromAPI(); applyColor(); }, applyColor: function() { for (var i=0; i<this.json.data.length; i++) { var doc = document.getElementById(t ...

Creating interactive web applications with Python Flask by utilizing buttons to execute functions

When the button is clicked in my Flask template, I want it to trigger a Python function that I defined in app.py. The function should be accessible within the template by including this code where the function is defined: Here is an example function in ap ...

Struggling to access FormData in php

I'm having trouble retrieving variables from FormData in PHP after making an AJAX call. What could be causing this issue? Here is the snippet of my JavaScript code: var sendData = new FormData(); sendData.append('itemid',$('select#sel ...

Traversing JSON Data using Vanilla JavaScript to dynamically fill a specified amount of articles in an HTML page

Here is the code along with my explanation and questions: I'm utilizing myjson.com to create 12 'results'. These results represent 12 clients, each with different sets of data. For instance, Client 1: First Name - James, Address - 1234 Ma ...

Switching between different months in the React-Calendar display

I've been working with React-Calendar and I'm facing an issue where the month doesn't change when clicking the navigation arrows in the calendar. Here's a snippet of my code: ... const onActiveStartDateChangeHandler = ({ activeStartDa ...

Using Vuejs 2 to manage assets

As a beginner in VueJS, I am exploring ways to incorporate an external JavaScript library into my component. After downloading the minified JS file and placing it in my assets directory, I'm unsure how to compile my component to utilize this library ...

Avoid navigating to the subscribe block when the server sends a response in Angular

When trying to send a request to the server and check the response, I am not seeing any results. The code for sending the request is below: SendVerificationInfo(item: SendVerificationModel): Observable < any > { return this.httpClient.post < any ...

Differences Between JavaScript and TypeScript Classes

I'm a novice when it comes to TypeScript and JavaScript classes! While learning TypeScript, I created a simple code snippet like this: class User { name: string; email: string; constructor(name: string, email: string) { this.name = name; ...

Enhance the php query limit using javascript when loading additional content

Hey there, currently working on implementing a reverse infinite scroll feature for a private messaging module. Everything seems to be functioning well, except for one issue I'm facing - struggling to update the query limit. I set the maximum and lim ...

Tips for updating the icon based on the active or inactive status in ag-grid within an angular application

HTML* <ng-template #actionButtons let-data="data"> <div class="cell-actions"> <a href="javascript:;" (click)="assign()"> <i nz-icon nzType="user-add" nzTheme= ...

Utilizing ng-href in Angular.js Template: A Guide

I am attempting to develop a simple Single Page Application (SPA) with just one index.html file that includes templates. However, I encountered an issue with the ng-href directive: <a ng-href="#/myPage">myPage</a> This works fine in index.h ...

What is the limit on the amount of input data (in CSV or JSON format) that can be used to create a

Attempting to visualize a large dataset using D3.js has posed a challenge for me. The data size is 261 MB with approximately 400,000 rows in CSV format. Even when I attempt to run it with just 100,000 rows, the visualization does not appear on the browser. ...