Check if the statement description on credit card statements is valid using regular expressions

I need to validate a user-entered string that will be used as the description on a credit card statement to describe a purchase.

Here are the requirements:

  • The string must be between 5 and 22 characters long
  • It should have at least one letter (uppercase or lowercase)
  • Special characters like <, >, \, ' and " are not allowed
  • Only ASCII characters can be used

Currently, I have a regex pattern that partially works:

/^(?=.*?[a-zA-Z])[a-zA-Z0-9]{5,22}$/gm

This pattern correctly validates the length and ensures at least one letter is present. However, it restricts all special characters and diacritics instead of permitting only the few that are not allowed. How can I modify it to allow the specified characters?

Answer №1

To ensure a character is present, you can utilize a positive lookahead, and to prevent matching any characters specified in the character class, you can use a negative lookahead.

In the context of JavaScript, you can enable case-insensitivity by adding the flag /i and working with [a-z].

Update: As highlighted by Wiktor Stribiżew, for restricting matches to ASCII characters only, consider using [\x00-\x7F] instead of a dot.

^(?=.*[a-z])(?!.*[<>\\'"])[\x00-\x7F]{5,22}$
  • ^ Denotes the start of the string
  • (?=.*[a-z]) Positive lookahead to confirm the presence of an ASCII letter
  • (?!.*[<>\\'"]) Negative lookahead ensures none of the characters in the class are matched
  • [\x00-\x7F]{5,22} Matches any ASCII character between 5 and 22 times
  • $ Marks the end of the string

For instance:

const regex = /^(?=.*[a-z])(?!.*[<>\\'"])[\x00-\x7F]{5,22}$/gmi;

Refer to the demonstration on regex101

Answer №2

Feel free to utilize

/^(?=[^a-z]*[a-z])(?:(?![<>\\'\"])[\x00-\x7F]){5,22}$/i
/^(?=[^a-z]*[a-z])(?![^<>\\'\"]*[<>\\'\"])[\x00-\x7F]{5,22}$/i

If you are considering allowing only printable ASCII characters, the following can be used

/^(?=[^a-z]*[a-z])(?:(?![<>\\'\"])[ -~]){5,22}$/i
/^(?=[^a-z]*[a-z])(?![^<>\\'\"]*[\lt;\gt;'"])[ -~]{5,22}$/i

Breakdown

  • ^ - denotes the beginning of the string
  • (?=[^a-z]*[a-z]) - requires at least one ASCII letter in the string
  • (?:(?![<>\\'\"])[ -~]){5,22}
    - specifies a range of five to twenty-two occurrences of any printable ASCII character excluding <, >, \', and \" (or other specified characters)
  • (?![^<>\\'\"]*[<>\\'\"])
    - ensures that none of the excluded characters are present in the string
  • $ - signals the end of the string.

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

Load information into array for jqGrid display

I am attempting to populate my JQgrid with data every time I click the "1" button, but I am encountering difficulties. As a newbie in jQuery, I am able to display the data in a p tag without any issues. Currently, I am considering whether to use push or a ...

Looking to deactivate the entire keyboard with JavaScript? Make sure that the start key is not disabled, not even Ctrl

Despite my efforts to disable the entire keyboard using JavaScript, I have encountered some limitations. The Windows Start key and Enter key are not being disabled by my script. <script type='text/javascript'> document.onkeydown = functi ...

JQuery submit event not triggering object setting

I'm looking to gather input values from a form and store them in an object for an offer. After trying the following code on submit: $(document).ready(function(){ $('#formOffre').on('submit', function(e) { e.preventDefault ...

What is the technique for incorporating FontAwesome icons onto an HTML 5 canvas?

I am encountering an issue while trying to use FontAwesome icons within my HTML 5 canvas. Here is what I have attempted: ct.fillStyle = "black"; ct.font = "20px Font Awesome"; ct.textAlign = "center"; var h = 'F1E2'; ct.fillText(String.fromCha ...

Firefox triggers drag events while passing over a div scrollbar

I am looking to create a file drag and drop feature using a styled div: When dragging files over the div, I want the border color to change When dragging files out of the div, I want the border color to revert back to the original In Firefox 35 (Ubuntu) ...

``Error: GraphQL server unable to initiate due to a failure in the module.exports

While learning GraphQL, I encountered an error when attempting to start a server. const graphql = require('graphql'); const _ = require('lodash'); const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLSchema } ...

Try enabling automatic status bar filling in Onsen UI when working with AngularJS

Completely new to AngularJS, I am trying to understand how to use ons.enableAutoStatusBarFill(); in order to prevent my menus from overlapping the status bar. This is how I have set up my controller: var mod = ons.bootstrap('app', ['onsen& ...

Navigate to the adjacent IDs

I have multiple sections with varying content and links (previous and next) to navigate to the next section. Initially, everything functions properly. However, when adding a new section in between existing ones, I am required to update all the ids to ensu ...

Need assistance with a coin flip using HTML and Javascript?

After spending hours trying to make the code work with the example provided, I find myself unable to get it functioning correctly. Is there anyone who can assist me in putting all of this together so that it runs smoothly? var result,userchoice; functio ...

Transferring information from nodejs/express to frontend JavaScript

I am faced with a challenge regarding accessing the 'data' sent from my backend server in my frontend js. Can anyone guide me on how to achieve this? Express ... app.get("/", (req, res) => { res.render("home", {data} ); }); ... home.ejs ...

"Validation with Express-validator now includes checking the field in cookies instead of the request

My current validator is set up like this: const validationSchema = checkSchema({ 'applicant.name': { exists: true, errorMessage: 'Name field is required', }, }); and at the beginning of this route (the rest is not relevant) ...

Unable to execute an Angular 2 application within Visual Studio 2015

I encountered an error while trying to set up an environment on VS 2015 with Angular2. Whenever I run the command "npm start," I receive the following error message. I attempted using "npm cache clean --force" before running "npm start," but the error pers ...

Incorporating multiple true statements into an IF ELSE structure can enhance the decision-making

I'm struggling with getting a true return value for numbers that are integers and have either 4 or 6 digits - no decimals or letters allowed. The issue seems to be the validation of whether it's really a number and if it has a decimal point. Alt ...

Obtain environment variables within a Strapi plugin

I am currently working on developing a Strapi local plugin, but I am facing an issue with retrieving variables defined in my .env file located at the root of my project. Specifically, I am trying to access this value within my React component (plugins/myPl ...

Steps to include a tooltip on a button that triggers a modal

I am currently utilizing Bootstrap and jQuery to enhance the functionality of components in my application. I am specifically looking to incorporate tooltips into certain elements. The tooltips are implemented through jQuery within my index.html page: < ...

Turning a Two Dimensional Object or Associate Array into a Three Dimensional Object using Javascript

Is there a method to transform the following: var stateDat = { ME: ['Maine',1328361], etc. }; Into this structure dynamically within a function? var stateDatHistory = { 1:[ ME: ['Maine',1328361], etc. ], 2:[ ME: ['Maine& ...

Alter the button ID based on the currently displayed div

My mind is being driven crazy by a particular issue I am experiencing. Let me explain... I have a lengthy scrolling page with approximately 10 divs stacked one after the other without any spacing in between. Positioned at the bottom of the viewport is a bu ...

Nested data selection in React

I have been experimenting with creating a nested select optgroup and attempted the following: const data = [ { sectorId: 5, sectorName: "Sector One", departments: [ { deptName: "Production", jobtitles: [ { ...

Trouble with Chakra UI loading Images from local sources

I'm running into issues when trying to load local images using the Chakra UI library in combination with Next.js. <Image src="./homepage/footer/Black.svg" /> Here is the current folder structure: When checking my console, I see the f ...

Development of a custom waterfall toolbar design using MUI framework

I've been working with a setup similar to the one found here: https://codesandbox.io/s/1op5mqq9oq By clicking on the checkboxes, the <Toolbar /> is displayed. As you scroll down the page, the <Toolbar /> remains fixed at the top and even ...