Javascript: regular expression to validate alphanumeric and special characters

Looking to create a regular expression for a string (company/organization name) with the following conditions:

  • No leading or trailing spaces
  • No double spaces in between
  • Shouldn't allow only a single character (alphanumeric or whitelisted)
  • Can start with an alphanumeric or whitelisted character
  • Shouldn't allow any whitelisted character to be entered multiple times

Here is the regex for these conditions:

/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('_')); // shouldn't allow

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('a')); // shouldn't allow

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc   abc')); // shouldn't allow

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('_123')); // works fine

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('# abc')); // works fine

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc abc!')); // works fine

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc abc# abc')); // works fine

The current regex does not meet all the criteria and it is unclear what the issue with the regex is.

Answer №1

Feel free to utilize

/^(?=.{2})(?!(?:[^_.#&!-]*[_.#&!-]){2})[a-zA-Z0-9_.#&!-]+(?:\s[a-zA-Z0-9_.#&!-]+)*$/

Particulars

  • ^ - beginning of the line
  • (?=.{2}) - the line must start with any two characters
  • (?!(?:[^_.#&!-]*[_.#&!-]){2})
    - there should not be two instances of _.#&!- characters in the line
  • [a-zA-Z0-9_.#&-]+ - one or more allowed characters (excluding whitespace)
  • (?:\s[a-zA-Z0-9_.#&!-]+)* - zero or more occurrences of
    • \s - one whitespace character
    • [a-zA-Z0-9_.#&!-]+ - one or more letters, digits, and certain symbols
  • $ - end of the line.

Check out the JavaScript demonstration below

var rx = /^(?=.{2})(?!(?:[^_.#&!-]*[_.#&!-]){2})[a-zA-Z0-9_.#&!-]+(?:\s[a-zA-Z0-9_.#&!-]+)*$/;
console.log(rx.test('_')); // should not be allowed
console.log(rx.test('a')); // should not be allowed
console.log(rx.test('abc   abc')); // should not be allowed
console.log(rx.test('_123')); // should work fine
console.log(rx.test('# abc')); // should work fine
console.log(rx.test('abc abc!')); // should work fine
console.log(rx.test('abc abc# abc')); // should work fine

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

Avoiding page refresh while submitting a form can be tricky, as both e.preventDefault() and using a hidden iFrame seem

I've been stuck on this issue for a while now, scouring Stack Overflow and Google for solutions, but nothing seems to be working. My main goal is to avoid page reloads after uploading a file because it resets the dynamic HTML I need to display afterwa ...

Small-scale vue iterates through elements with v-for but fails to display them

I'm really interested in Petite-vue, but I've been struggling to get even the basic functionalities to work. Unfortunately, there isn't a lot of examples or tutorials available online for petite-vue. Can anyone suggest good resources? Right ...

Display a fixed three levels of highchart Sunburst upon each click in Angular8

Looking to create a dynamic sunburst highchart that displays three levels at a time while allowing interactive drilling. For instance, if there are 5 levels, the chart should initially show the first three levels. When clicking on level 3, levels 2, 3, and ...

Toggle the image and update the corresponding value in the MySQL database upon clicking

Looking to implement a feature that allows users to bookmark pages in my PHP application using JavaScript. The concept involves having a list of items, each accompanied by an image (potentially an empty star). When a user clicks on the image, it will upda ...

Developing a unique JavaScript object by extracting information from a jQuery AJAX response

Is there a recommended approach for creating a custom JavaScript object that contains data retrieved from a jQuery AJAX request? I'm considering two methods, but unsure which is the most appropriate. The first method involves including the AJAX reques ...

Error: Attempting to access a property 'notesObjectInService' that is undefined on the object

I'm currently facing an issue where my controller is unable to load an object from a service called notesFactory. The console.log(typeof notesFactory) statement returns 'undefined', causing notesObjectInService to trigger an exception. Desp ...

Multi-line D3 chart that dynamically updates and intersects with the axis

I am attempting to create a multiline d3 chart that can be updated with new datasets. I have developed a method to plot the new data on the existing d3 frame, but I am encountering issues when trying to update the chart with mocked data. The new data is no ...

What could be the reason for the failure of Angular Material Table 2 selection model?

A Question about Angular Mat Table 2 Selection Model Why does the selection model in Angular Mat Table 2 fail when using a duplicate object with its select() or toggle() methods? Sharing Debugging Insights : Delve into my debugging process to understand ...

Modifying multiple objects with Vue's V-Model

When utilizing the mounted function in Vue to assign two different objects in the data area and bind one of them to a form, an unusual issue arises: Both objects change when input values are entered in the form For example: <template> <v-card ...

Vue.js and TypeScript combination may result in a 'null' value when using file input

I am attempting to detect an event once a file has been uploaded using a file input. Here is the JavaScript code: fileSelected(e: Event) { if ((<HTMLInputElement>e.target).files !== null && (<HTMLInputElement>e.target).files[0] !== null) { ...

Encountered an issue while attempting to send a POST request using AngularJS $

I am facing an issue with accessing the POST method from my server. Whenever I log the response, it always returns status=0. Can anyone help me out or provide some advice? Note: I have tested the method in Postman and it works fine. Below is the code snip ...

Can one extract a property from an object and assign it to a property on the constructor?

Currently working with TypeScript, I am looking to destructure properties from an object. The challenge lies in the fact that I need to assign it to a property on the constructor of the class: var someData = [{title: 'some title', desc: 'so ...

Challenges with handling JSON data in JavaScript

I am currently attempting to retrieve and parse JSON data in order to display it on a blank HTML file. Unfortunately, I keep encountering an issue where if I retrieve and parse the data, I receive an error stating Uncaught TypeError: Cannot read property & ...

Pressing the submit button in the Material UI table clears all selected checkboxes

Take a look at this code snippet: https://jsfiddle.net/aewhatley/Lkuaeqdr/1/. My objective is to construct a table with a submit button utilizing Material-UI components. const { Table, TableHeader, TableHeaderColumn, TableBody, TableRow, Table ...

The multi update feature is only compatible with $ operators when performing bulk find and update operations in node.js, as indicated by the Mongo

Why am I receiving the error message MongoError: multi update only works with $ operators when attempting to update multiple documents using the bulk find and update method. Things I have tried: var bulk = db.collection('users').initialize ...

Organize array by year and month groupings

I'm trying to organize an array of events by year and month. Here is a sample of my data: const events = [ { name: "event 1", year: 2021, month: 1, }, { name: "event 2", year: 2021, month: 9, }, { ...

The subsequent block within the code is being initiated following the initial block in Node.js

It was expected that "1" would be printed before "2", but the output is incorrect. fs.readdir("./my_stocks", (err, files) => { for(each in files){ var file=files[each]; if(file!='portfolio.js'){ var fn="./my_sto ...

Conceal Bootstrap Toast for a day following dismissal

I have implemented Bootstrap 5 toasts to showcase an advertisement on my website. The goal is to make the advertisement disappear for 24 hours once the user closes it. Here's the current code snippet: <div class="position-sticky bottom-0" ...

When calling a Vue.js method, it appears to be undefined

Currently, I'm working on developing a Chrome extension using Vue and Browserify. Within my component file, I'm attempting to invoke a method called animateBackground from the mounted hook. However, when checking the console, an error message is ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...