The regular expression pattern for the input element is not functioning properly

I need the input field to turn green only when it contains 4 letters followed by 4 numbers, like "abcd1234".

The regular expression code I tried is: [A-Za-z]{4}+[0-9]{4}.
I also attempted this code: ^[A-Za-z]{4}+[0-9]{4}$.

Below is the CSS code I'm using:

 input:invalid {
  background: hsla(0, 90%, 70%, 1);
}

input:valid {
  background: hsla(100, 90%, 70%, 1);
}
<input type='text' required name='username' autocomplete="off" id='username' pattern="[A-Za-z]{4}+[0-9]{4}" maxlength="50" />

However, the field doesn't change to the :valid state as expected.

Answer №1

The + in your regex is excessive. Try using either [A-Za-z]{4}[0-9]{4} or [A-Za-z]{4}\d{4}

input:invalid {
  background: hsla(0, 90%, 70%, 1);
}
input:valid {
  background: hsla(100, 90%, 70%, 1);
}
<input type='text' pattern="[A-Za-z]{4}[0-9]{4}" required name='username' autocomplete="off" id='username' maxlength="50" />

<!-- Use shorter regex -->
<input type='text' pattern="[A-Za-z]{4}\d{4}" required name='username' autocomplete="off" id='username' maxlength="50" />

Answer №2

[A-Za-z]{4}: Representing an alphabet character repeated 4 times.

+: Indicates matching one or more occurrences. However, using [A-Za-z]{4} followed by + is an incorrect pattern.

[0-9]{4}: Denotes numeric characters being repeated 4 times. This can also be expressed as \d{4}.

Furthermore, the required attribute can be removed since it is included in the pattern itself.

The proper regex would be: [a-zA-Z]{4}[0-9]{4} or [a-zA-z]{4}\d{4}

Answer №3

Give this a shot too,

<input type='text' pattern="[A-Za-z]{4}\d{4}" required name='username' autocomplete="off" id='username' maxlength="50" />

You might want to test out this regular expression as well, although it may not be compatible with all text editors,

[\u\l]{4}\d{4}

The part [\u\l] will match both uppercase and lowercase letters.

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

Modifying HTML tags: substitution or deletion

Looking for a solution to clean up messy HTML that was generated by a machine. I'm thinking regex might be the way to go, but I don't know where to begin. The original HTML looks like this... the <div>government’s</div> “risk m ...

Is there a way to dynamically update the content of <li> tag with values from an array every x seconds

I am trying to create a li list using jQuery that will update every 2 seconds with new content, similar to game news updates. However, I'm encountering an issue during the first cycle where it skips the second item in the array. The subsequent cycles ...

Display the gridview using <div> elements rather than tables

Does anyone have a code snippet that can display a gridview within a <div> element instead of a table? I would greatly appreciate any assistance with this. I am trying to create a graph similar to the one I have included and would like some functi ...

When a PHP-generated child element is clicked, jQuery fails to detect it

I'm currently developing a website where I need to dynamically display buttons based on database content. These buttons, when clicked, should send a request to the database and update the page content accordingly. My approach involves using Ajax and ...

Consistently showcasing images of varying dimensions that are unfamiliar

Currently, I'm in the process of developing a small web application that uses the Spotify API to fetch and showcase top tracks and artists to users. Each track or artist is presented within a Bootstrap panel, with the title displayed in the header an ...

Prevent the activation of div elements with identical attributes

I have created two separate div elements with unique IDs, but they share the same attributes. Below is the structure of the first div: <div id="espresso-option" class="option"> <div class="container"> <div ...

Press the "Print All" button to instantly print out all of the images in one go

I have successfully implemented a feature where multiple images are displayed as thumbnails from a specified folder. Now, I am looking to add a "Print All" button that will allow users to print all the images in one go. Is it possible to print all images ...

Distinguishing $(document).width() and $("html").width() in jQuery on Internet Explorer 11

There seems to be an issue with IE11... APPROXIMATED (I presume...) console.log($(document).width()); // 808px; EXACT VALUE console.log($("html")[0].getBoundingClientRect().width); // 807.30993px; ROUNDED DOWN (or to the nearest whole number) console ...

Creating clickable links with Regex for 'a href' tags only, excluding 'img src' tags

After extensive effort, I am still struggling to find a reliable solution for my issue. The task at hand is to convert all http/https links within a string into clickable links, specifically targeting only those embedded in the 'href' attribute o ...

Creating CSS dynamically using PHP

Even after reading numerous blogs and forums, I'm still unable to get this working. My goal is to allow users to personalize their user account style sheet. I made sure to include <?php header("Content-type: text/css"); ?> at the beginning of t ...

PHP: Issues with displaying data from a SELECT * FROM query in tables

My goal is to style tables pulled from my database so that the columns in the rows align with the column names for better readability. I attempted to use PHP to achieve this by creating a table outside a while loop to display the names and then starting t ...

Alignment of grid with absolute images in Bootstrap

Hello there! I am relatively new to the world of coding and also to this platform, so please forgive any mistakes I may make along the way. Recently, I've been working on a project to create a site similar to Picrew, but I seem to have hit a roadblock ...

Steps to add a background image without a border:

I am struggling to insert an image within an anchor tag. <a> <img calss="imageclass"/></a> Whenever I try, a border appears around the image. I have attempted using CSS properties like border: 0 and border-style:none, but nothing seems ...

Exploring the concepts of Html5 semantic elements

After spending years programming websites with HTML 4, I finally decided it was time to upgrade my skills and transition to HTML5. Unfortunately, older browsers don't support HTML5, but I discovered a JavaScript file called "html5shiv" that can help b ...

The Bootstrap modal-backdrop dilemma requiring JavaScript intervention

I am encountering some problems with the Bootstrap modal. When I try to open a modal, everything looks good, but when I close it, the screen turns completely black. Upon closer inspection, I found that every time I click on the X to close the modal, there ...

Discovering a location on Google Maps using a postal code in a particular country

In the past, I used a method that involved adding a postal code to the end of a Google Maps link to view a specific location. For example, if the postal code is 649414, I would add it to the following link: https://www.google.com/maps?q=649414. However, I ...

How is it possible that changing my grid-template-row settings is causing an impact on the

I'm currently working on configuring the rows to have a grid-template-rows: 30px 1fr; setup, where the first row is set to 30px and all subsequent rows adjust their height accordingly. However, I've noticed that this styling seems to be impacting ...

HTML template with three columns where the content spills over the edges, despite having a visible border and a height of 100%

I have a wrapper containing 3 divs: <div id="wrapper"> <div id="leftbar"> Lorem ipsum dolar sit amet </div><!--LEFTBAR--> <div id="middle"> Lorem ipsum dolar sit amet </div><!--middle--> <div id="rightbar"&g ...

Using html-mode in emacs to create a hyperlink

My image src text in emacs has become clickable. I would like to have plain text instead. How can I disable this feature? <img src="index_new_menus_files/menu_bg_2.gif" alt="" border="0" height="55" width="150"> Instead, I want it to be: <img s ...

Displaying content on a webpage using PHP, AJAX, and HTML

Looking to update my current form setup. I have a basic Form below: <form action="" method="POST"> <input type="button" value="Generate Numbers" onclick="on_callPhp1()"/> </form> Accompanied by this javascript code: <script type="te ...