Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle registration number without allowing incorrect entries. An example of the desired output is:

HR 23 DU 2323

vehicleNumberFormat() {
    const { value } = this.myForm.get('vehicleNumber');
    console.log('value', value);

    const regex = /^(\w{0,2})(\w{0,2})(\w{0,2})(\w{0,4})$/g
    // const onlyNumbers = value.replace(/[^\d]/g, '')
    const typedValue = value.replace(/[^\w]/g, '')

    const formatedVehicleNumber = typedValue.replace(regex, (regex, $1, $2, $3, $4) => 
      [$1, $2, $3, $4].filter(group => !!group).join(' ')
    )

    console.log('formatedVehicleNumber-->', formatedVehicleNumber.toUpperCase())
    this.myForm.controls['vehicleNumber']?.setValue(formatedVehicleNumber.toUpperCase());
    
    return formatedVehicleNumber;
  }

Check out the codebase on StackBlitz

Answer №1

My solution to your requirement is to use the following regular expression:

^([a-zA-Z]{2})\s+(\d{2})\s+([a-zA-Z]{2})\s+(\d{4})$

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

Achieving a transparent inner box-shadow effect on hover: a step-by-step guide

Is there a way to make the black ring transparent upon hover by changing box-shadow: 0 0 0 5px #000, 0 0 0 10px green to box-shadow: 0 0 0 5px transparent, 0 0 0 10px green? It doesn't seem to be working for me. Any suggestions on how to achieve this ...

Learn the process of dynamically updating the source of an HTML5 video

Currently, I am working on a project that involves dynamically loading multiple videos onto a webpage. The structure of my HTML is quite straightforward - it consists of a single video tag. <video controls preload width="520" height="350" id="video"> ...

Personalize the Ag-Grid Status Bar to your liking

Currently utilizing Ag-Grid Enterprise, Version 19 ("ag-grid-angular": "19.0.0", "ag-grid-community": "19.0.0", "ag-grid-enterprise": "19.0.0") in conjunction with Angular 4. There is a specific need to customize the status bar of the grid and add an add ...

Incorporate an external object not native to the Angular framework within a factory

We're in the midst of a debate and I'm hoping you can help us reach an agreement. Imagine I have a basic factory set up like this: angular.module('myModule', []) .factory('Fact', function() { var Fact = function() { ...

Manage text, PDF, and image files in a MEAN stack app by uploading and fetching them from a MongoDB database using

I have been working on developing a piece of code that allows users to create a dynamic URL, upload a file by clicking a button on the page, and then download the same file in the same format when revisiting the URL. The functionality is similar to cl1p, b ...

The G/L account specified in the SAP B1 Service Layer is invalid and cannot be used

I attempted to generate a fresh Incoming payment utilizing the service layer, but encountered this issue G/L account is not valid [PaymentAccounts.AccountCode][line: 1] Here is my JSON: { "DocType": "rAccount", "DueDate& ...

Media publications do not conform to the current trends

I'm currently utilizing the HTML-to-paper plugin to print my content on a printer. However, I've encountered an issue where it doesn't seem to apply any of the styles I've defined within @media print. The challenges I'm encounteri ...

Tips on extracting the ID number prior to locating an element by its ID using Python Selenium

I am currently attempting to automate sending LinkedIn connection requests using Python with Selenium. However, I am facing an issue where the ember number value keeps changing every time I try to copy the id of the button. Sometimes it shows as #@id=" ...

Issues arise while utilizing the execute method in PHPUnit-Selenium2

When creating Acceptance tests with PhpUnit and its Selenium2 extension, I am attempting to utilize the execute method within the PHPUnit_Extensions_Selenium2TestCase class to run Javascript code that checks if the document is fully loaded. Here is an exa ...

Issues with the visibility of inlined styles within the Angular component library

After developing a custom library with components for an Angular 4 application, I encountered an issue where the CSS styling from the components was not being applied when using them in an application. Although the functionality worked fine, the visual asp ...

Oops! The 'map' property cannot be found in the type 'Observable<User>'

In my online shopping project that combines Angular and Firebase, I implemented the AuthGuard to verify user login status before accessing various links including ./check-out. However, I encountered an issue with importing map for Observable.User. All comp ...

Dealing with models in Vue.js is proving to be quite a challenge

Why isn't myGame showing as 超級馬力歐 initially and changing when the button is pressed? It just displays {{myGame}} instead. I'm not sure how to fix it, thank you! let myApp = new vue({ el:'myApp', data:{ myGame:&a ...

We were unable to locate the module '@reactflow/core' or its associated type declarations

After forking reactflow, I attempted to make some modifications but encountered a type error even without making any changes. My next step was to try "pnpm i @types/reactflow," but it did not resolve the issue. ...

Once an AJAX call is made, the state of a React component changes but fails to trigger a

In this section, users have the opportunity to comment on posts. Once the data is received and verified on the server side, I attempt to update the value of this.state.comments. However, there is an issue where the comment section in the component does not ...

Develop a JSON parsing function for VUE reusability

Currently, I am iterating through an array in Vue that contains objects with strings nested within. These objects have various properties such as idType, type, user, visibility, seller, product, company, and additionalData. notifications: [ 0: { idTy ...

A guide to configuring VSCode to recognize the DefinitelyTyped global variable (grecaptcha) within a Vuejs 3 TypeScript project

I have recently set up a new project using Vue.js 3 and TypeScript by running the command npm init vue@latest. I now want to integrate reCaptcha v2 into the project from scratch, without relying on pre-existing libraries like vue3-recaptcha-v2. Instead of ...

How do I insert a new item into the tree structure using Sapui5 CustomTreeItem?

Having an issue with the CustomTreeItem in SAPUI5. I can successfully display the tree structure from JSON, but struggling to manually add data on click of the Add button. In the image above, when I click the + Button, I need to add a Tile below it. Howev ...

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

What could be the reason why the Google Maps API fails to load on Firefox?

I am currently utilizing the v3 version of Google Maps API. While my map functions perfectly in Safari and Chrome, I encountered an issue in Firefox where I received the error message "google.maps.Map is not a constructor." When inspecting 'google.ma ...

Issue with datepicker initialization causing format not to work in Bootstrap

I am currently incorporating the angular-bootstrap datepicker module into my app and have run into a minor issue. I am using an input text field and a button to display the date in the following manner: <div class="row" id="datePicker"> <p cl ...