Guide to utilizing Regex validation for checking the vehicle registration plate in Vue 3 input field

I need to implement validation for an input field that only accepts capital letters and numbers, following a specific format (AAA-111). The first 3 characters should be alphabets, followed by a hyphen, and then the last 3 characters should be numbers.

<template>
  <div class="mt-6">
    <input
      type="text"
      placeholder="XXX-XXX"
      class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
      v-model="number_plate"
    />
    <br />
  </div>
</template>
<script>
export default {
  props: ['template'],
  data: function() {
    return {
      number_plate: '',
      regex: '^[A-Z]{3}-d{3}'
    };
  },
  watch: {
    number_plate() {
      this.number_plate = this.number_plate.match(/(^[A-Z]{3})(\d{3})/g, '$1-$2');
    }
  }
};
</script>

I've attempted to use a solution but encountered issues since I'm new to Vue. Any help would be appreciated.

After following a tutorial and adapting code for number validation with a specific pattern, I faced difficulties making modifications. The first input field functions correctly displaying numbers in the format 000-000, but the second one doesn't work as expected for AAA-000.

<template>
  <div class="mt-6">
    <input
      type="text"
      :placeholder="number_template"
      class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
      v-model="number"
    />
    <br /><br />
    <input
      type="text"
      :placeholder="reg_template"
      class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
      v-model="number_plate"
    />
  </div>
</template>
<script>
export default {
  props: ['number_template', 'reg_template'],
  data: function() {
    return {
      number: '',
      number_format: '', // number pattern for now XXX-XXX
      regex: '', //regex for number pattern
      reg_regex: '', // regex for registration plate number
      reg_format: '', // pattern for registration number for now XXX-XXX (first 3 are letters and last 3 are numbers)
      number_plate: ''
    };
  },
  mounted() {
    let x = 1;
    this.format = this.number_template.replace(/X+/g, () => '$' + x++);
    console.log(this.format);
    this.number_template.match(/X+/g).forEach((char, key) => {
      this.regex += '(d{' + char.length + '})?';
      console.log(this.regex);
      console.log(char.length);
      console.log(key);
    });
    let y = 1;
    this.reg_format = this.reg_template.replace(/X+/g, () => '$' + y++);
    console.log(this.reg_format);
    this.reg_template.match(/X+/g).forEach((char, key) => {
      this.reg_regex += '(d{' + char.length + '})?';
      console.log(this.reg_regex);
      console.log(char.length);
      console.log(key);
    });
  },
  watch: {
    number() {
      this.number = this.number
        .replace(/[^0-9]/g, '')
        .replace(/^(\d{3})?(\d{3})/g, this.format)
        .substr(0, this.number_template.length);
    },
    number_plate() {
      this.number_plate = this.number_plate
        .replace(/([A-Z]{3})?(d{3})/g, this.format)
        .substr(0, this.reg_template.length);
    }
  }
};
</script>

Answer №1

Vue is not required for this particular task. HTML alone can handle it adequately. However, if you require specialized validation, that's a different story. Consider implementing this code snippet directly in the template:

<input
      type="text"
      placeholder="XXX-XXX"
      pattern="^[A-Z]{3}-d{3}"
      class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
      v-model="number_plate"
    />

Additionally, the origin of this.number remains unclear.

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

Encountering difficulty inserting ajax response into a specific div element

What could be the issue? I've included the getElementById and I am receiving a response, as confirmed by Firebug. The response is correct, but for some reason it's not populating my div area. <script> $(document).ready(function () { $( ...

Issue with Ajax form submission on one specific page

My form submission using JQuery AJAX is causing my page to redirect to submit.php instead of staying on the current page. I have tried various solutions but cannot pinpoint the issue... The PHP script seems to be working fine, with only one echo statement ...

In Visual Studio, make sure to include a reference to AngularJS.min.js within another JavaScript file

In my AngularJS app, I am utilizing Visual Studio with separate folders. The AngularJS-min.js file is located in a different folder. My query is how can I correctly reference the AngularJS-min.js file in my app's JavaScript file to enable auto-suggest ...

VuePress - markdown document imbued with unique symbols

As I was attempting to follow the get-started tutorial for VuePress, I encountered an unexpected result when running the application for the first time: # Hello VuePress I thought it might be a PowerShell issue, so I modified the text. However, the outpu ...

Why is My TensorFlow.js Model for Predicting 2 Table Multiples Not Producing Accurate Results?

I have created a tensorflow.js model that predicts outputs in multiples of two. For example, if the input is 16, the prediction should be 32. However, even after providing the input data and labels accordingly, the output printed is [[1],] after prediction ...

Ways to pinpoint a particular division and switch its class on and off?

Consider this scenario, where a menu is presented: function toggleHiddenContent(tabClass) { let t = document.querySelectorAll(tabClass); for(var i = 0; i<t.length; i++) { t[i].classList.toggle="visible-class"; } } .hidden-conten ...

Irreparable Glitches in Mocha

While developing a blogging platform, everything ran smoothly when tested on a web server. However, I encountered some issues when trying to write unit tests using Mocha and Should.js. Surprisingly, errors kept popping up where they shouldn't have bee ...

What strategies should be employed to manage data-driven input in this particular scenario?

In the process of creating a small webpage, I have designed 2 navigation panels - one on the left and one on the right. The leftNav panel contains a list of different flower names. While the rightNav panel displays images corresponding to each flower. A ...

Information displays instantly in the initial milliseconds

When developing dynamic web pages with Nuxt, I encountered an issue in the pages directory where a file named _url.vue is located. The contents of this file are as follows: <template lang="pug"> div component( v-for= ...

Issue with PHP Upload: Index is undefined

Having Trouble with PHP Upload: Encountered an issue: Undefined index: file in Error on line: $count = count($_FILES['file']['name']); Tried numerous codes to fix this error, but none have worked so far PHP Code: <?php $count ...

Troubleshooting VueJS's Dilemma with Quotation Marks

When I try to parse a string containing either double quotes or single quotes, an error is being thrown: JSON Unexpected token. Is there a way to properly parse and bind it to a variable in Vue.js? PHP $arr = array(); $arr[0]['description'] = ...

Every time I use JSON.stringify on an object, I end up with a wild and wacky string returned

Whenever I attempt to transmit an object containing an array of objects from my express route to the client, I receive an [Object object]. Then, when I try to convert it into a string using JSON.stringify, I end up with a convoluted string along with a con ...

Showing JSON Array Values in a Table

I have created an array and am attempting to display its values in a table. Initially, my solution only displayed a single value from the array that matched an exact ID. You can see this implementation at (). Entering "jjones" would yield a result. I then ...

Missing transitive dependencies have been identified within the node_modules directory when using npm

In my software development journey, I am working on two npm projects - one called X and the other called Y. Let's say that X relies on angular and has it specified as a dependency in its package.json file. To establish a connection between X and Y, I ...

Is there a way to incorporate a text box in javascript that displays the retrieved reference count from the database?

I'm currently working on creating a functionality that retrieves rows with the same ID from a database and displays them in a text box. Below is the PHP code I've written for retrieving all the rows: PHP: <?php include_once('pConfig ...

Implementing vote functionality in Vue.js without page refresh

I am facing an issue with voting on my page. When I try to vote, I have to refresh the page for my vote to appear. Does anyone have any suggestions on how to make the vote show up without having to refresh? In the view, I loop through comments: @foreach($ ...

Tips for adding a form reset feature in JSF with PPR functionality and validators

Within my <tr:form>, I have various fields with validators, such as the built-in validator for <tr:inputDate>. Additionally, there is AJAX/PPR functionality in place, using partialTrigger attributes to dynamically update certain combo box choic ...

Steps for setting up single sign on in an Angular 2 application

Currently, I am working on a web application that has been developed using angular2. One of the requirements for this application is to incorporate a single sign-on feature, where users do not have to manually input their login credentials. Instead, the ap ...

Using Selenium and Python to download audio files that require JavaScript to load

Currently, I am in the process of developing a script to streamline the task of downloading text and audio files from a specific website using Python and Selenium. The targeted website is: (yyyymmdd) import requests from time import sleep from selenium ...

Design a button for removing the selected value in select2

Can anyone provide some guidance on using select2? I am working with 2 select2 elements, and I want the selected value to be displayed on a button instead of in the input area of the select2. This way, the select2 will still display the placeholder text. ...