Unexpected behavior observed with negated character: ? ^

I am looking to create a form where users can input their phone number and have the flexibility to choose how they want to separate the numbers. I have been using a regex pattern for validation:

var regex = /[^0-9 \/-\\\(\)\+]/;

While this regex works in most cases, there are situations such as @, :, and ; where it doesn't behave as expected. Any suggestions on how to improve this?

Here is an example to illustrate the issue.

testvar = '123@213';
var regex = /[^0-9 \/-\\\(\)\+]/;
if(regex.test(testvar) === true) 
    { alert('Chars out of regex-range found'); } // won't fire!

Answer №1

There is quite a journey from using / to switching to use \. But if that was your intention, then it's spot on. However, if not, you might be forgetting a slash before the dash:

const regex = /[^0-9 \/\-\\\(\)\+]/;

Answer №2

The phone number should only consist of digits, so it's best to disregard any formatting and retain only the numerical values.

var phoneNumber = value.replace(/\D+/g,'');

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

Use JavaScript regex to replace a string only if its length exceeds a certain specified limit

My current approach involves using JavaScript regex to insert an HTML markup for all identified URLs: var exp = /(((|www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|&bso ...

Can conditional statements be utilized within a React component?

Using Material UI, the CardHeader component represents the top part of a post. If the post is created by the user (isUser = true), I would like to display two buttons on the post. Is this achievable? <CardHeader avatar={ <Avatar sx={{ ...

Change the price directly without having to click on the text field

Our Magento marketplace site is currently utilizing the code below for updating prices. However, we are looking to make the price field editable without requiring a click on the textfield. This means that users should be able to edit the price directly wi ...

Loop stops after completing one iteration

I am currently working on a program that automatically generates ASCII text based on input numbers. Essentially, when a number is provided as input to the function, it will be displayed as magnified ASCII text. For example, an input of 0123456789 would gen ...

Oops, it seems like there was an issue with NextJS 13 Error. The createContext functionality can only be used in Client Components. To resolve this, simply add the "use client" directive at the

**Issue: The error states that createContext only works in Client Components and suggests adding the "use client" directive at the top of the file to resolve it. Can you explain why this error is occurring? // layout.tsx import Layout from "./componen ...

Angular 14 is experiencing issues with NgRx Store failing to properly recognize the payload

The issue lies in TypeScript not recognizing action.payload.index as a valid property. I am unsure how to resolve this problem and make the 'index' visible in my project. shopping-list.actions.ts import {Action} from "@ngrx/store"; im ...

When using an `if` statement in CSS to determine if the value of `left` is

Is there a way to trigger an event only when the object reaches a specific percentage of its left position? I am trying to achieve this using jQuery with the .css() method. Here is what I have so far: HTML: <div id="midDiv"><img ..../></di ...

Unable to retrieve accurate information

I am currently in the process of developing an application that utilizes Spring Boot and ReactJS. I encounter an issue where, despite entering correct data values in the form on the client side using the POST method, the response displays NULL values. Upo ...

Incorporating geocoding functionality in an asp.net mvc project and looking to efficiently transfer latitude and longitude data from JavaScript to a controller function

UPDATED. Following your suggestions, I implemented the function as shown below: [HttpPost] public ActionResult populate_place(string lati, string longi) { list_placesModels list_place = new list_placesModels(); list_place.Latitude = lati; li ...

What could be the reason for rowsAffected not returning an integer value?

Currently, I am working on executing the SQLite statement in an iOS application. To verify the count of affected records, I have implemented success and error callback methods. Upon receiving the results, although the variables are correctly defined, I en ...

Ways to invoke Java function using Javascript (Client-side)

I have a Java Swing application that handles the User Interface, but requires JavaScript files for hardware testing. The application calls a JavaScript engine to execute functions using the `InvokeFunction()` method. Currently, I am utilizing the LabJack ...

I am having trouble establishing a connection to the JavaScript MQTT server

Error Encountered: WebSocket Error 12031 - The Server Connection Was Reset In order to subscribe to MQTT messages from the user interface, the code below is being utilized. A Mosquitto broker is currently running on my local machine, with the IP address s ...

Having issues with ASP.NET MVC AJAX PartialView not loading Telerik UI components

I am facing an issue with a PartialView that I update using AJAX. The HTML elements load correctly when updating the Div with AJAX, but the Telerik chart is not loading. The datasource in the chart does not call the Action method: .DataSource(ds => ds. ...

Switch between Coordinated Universal Time and a designated time zone using the New Internationalization API

I am experimenting with the new Internationalization API using Chrome Version 31.0.1623.0 canary. My goal is to: Convert Date Time between UTC and a specific time zone (America/New_York as an example). Determine if the conversion takes into account Dayl ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

Is Passport.js' serializeUser and deserializeUser functions never triggering?

Encountering an issue with Passport-local. It seems that neither serializeuser nor deserializeUser are being invoked. Upon researching similar problems on SO, it appears that many others facing this problem were not properly including bodyParser. Below is ...

What is the method for identifying the name of a CSS Variable currently in use?

Consider this code snippet: /* css */ :root { --text-color: #666666; } input { color: var(--text-color); } In Javascript, how can I determine the name of the CSS custom property (variable) being utilized? // javascript console.log(document.querySel ...

When converting JavaScript to PHP using AJAX, PHP retrieves an empty array

I am attempting to send a file from JavaScript to PHP using AJAX, but PHP is receiving an empty array. Currently, I am working on creating a web page through which I can pass a file to PHP in order for it to access and save information from the file into ...

Using v-model in Vue 3 will result in modifications to the table class in Bootstrap 5

Below is a snippet of the code I wrote: <table class="table table-striped"> <tr class="table-dark"> <th>#</th> <th>Column 1</th> <th colspan="3">Column 2</th> </tr> <tr ...

Determine the current whereabouts and actions of the specified user

I am in the process of developing a command for my Discord JS bot that, when activated, will fetch the current game (or status if no game) of the user mentioned in the command. Subsequently, the bot will send a message stating Mentioned User has been playi ...