Tips for verifying a text box in Vue3 with Regex

Is it possible to implement custom input field validation using Regex? I aim to restrict the input field to three alphabets followed by three numbers, separated by a hyphen. Additionally, I want this validation to occur in real-time as the user types.

While I have found solutions for validating numbers, combining alphabet and number validation has proven challenging. Moreover, I want the input field to validate with each keystroke.

<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>

The code successfully validates the first input field but encounters issues with the second one. There might be necessary modifications within the mounted function where the reg_regex is handled, though I am unsure of how to proceed.

Answer №1

Web browsers have built-in native support for this through the pattern attribute:

<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"
  pattern="\w{3}-\d{3}"
/>

As the user types, this functionality will validate the form input on the client side.

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

leveraging dynamic variables within route elements in Vue 3

I have been utilizing this breadcrumb template in my project: <route> { name: "educations-view-id-tab", meta: { pageTitle: 'Educations', breadcrumb: [ { title: 'List', to:{ name: 'educations' }, disabled:false ...

Ensure that Ajax is updated when the document is ready

Upon document loading, the page initiates an ajax call to display a table of results. Updating rows can be done by clicking on a button, which triggers a function to post the update to the server. I had this functioning properly without wrapping the clic ...

Is it possible to use a shell script to replace the external CSS file link in an HTML file with the actual content of the CSS file

Seeking a solution for replacing external CSS and JS file links in an HTML document with the actual content of these files. The current structure of the HTML file is as follows: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C ...

Node.js encounters a failure when trying to set headers after they have already been sent in an HTTP request

Attempting to request a server using https/http and display the result on a web page. The script works fine on a server but fails when trying to return the result with a get request. var express = require('express'); var app = express(); var por ...

Error message: Unhandled error - $(...).sidr does not exist as a function. [Chrome developer console]

I included this code in the basic module HTML block of a WordPress page builder and encountered the white screen of death. According to the Chrome developer console, the following error occurred: helpers.js?ver=4.5.3:15 Uncaught TypeError: $(...).sidr is ...

Struggling to modify a nested object in the state

import React, { Component } from 'react'; import ColorBox from './ColorBox' import './ColorBoxes.css' class ColorBoxes extends Component { state = { colors: {} } clickedColor = (color) => { le ...

Hide jQuery dropdown when mouse moves away

I am working on designing a navigation bar with dropdown functionality. Is there a way to hide the dropdown menu when the mouse pointer leaves both the navbar menu and the dropdown itself? I have tried using hover, mouseenter, and mouseleave but due to my ...

Utilize Vuejs and Axios in Laravel to dynamically populate the form fields with the current user's information

I am looking to populate the form fields with current user information using Vuejs, Laravel, and Axios. Within the UserController.vue file, I have this code to retrieve the authenticated user's information from the API : public function profile() ...

Modify the initial letter of the user input as it is entered using JQuery

I've been experimenting with auto-capitalizing the first character that a user inputs in a textarea or input field. My initial approach was as follows: $(document).ready(function() { $('input').on('keydown', function() { if ( ...

Is there a way to verify if the meteor.call function was executed successfully?

In my meteor/react application, I am working with two components. I need to pass a method from one component to the other: saveNewUsername(newUsername) { Meteor.call('setNewUsername', newUsername, (error) => { if(error) { ...

What is the best way to attach an event listener to every child node within a div that is stored in an array of divs?

Currently, I am dedicated to learning JS on my own and have decided to hold off on using jQuery until my JavaScript skills have improved. The objective is to attach an event listener for the click event to all divs of a specific class and have all child n ...

What is the best way to automatically close a modal in vue.js after data has been successfully updated?

I am a novice in vue.js and I am facing an issue with closing the modal after updating the data. I have written the following code for pencil: <i class="mdi mdi-pencil" @click.prevent="$bvModal.show(type.title)" ></i> ...

Choosing HTML Elements for Audio Playback in HTML5: A Guide to Selecting Elements Without Using Div IDs

When creating an HTML5 player, I am transitioning "from using divs with id's" to "simple HTML elements". Former Scenario (functional) <audio src="track1.mp3" id="audio"></audio> <controls> <play id="play" style="display:none ...

"Exclusive Mui sx styles will be applied only when a specific breakpoint

As I update my old mui styling to utilize the sx attribute, I've noticed the ability to specify styles for different breakpoints using sx = {{ someCssProp: { xs: ..., md: ... and so on. Prior to this, I had been using theme.breakpoints.only for some ...

Is it possible to implement smooth scrolling in HTML without using anchor animation?

Is it feasible to implement a more seamless scrolling experience for a website? I'm referring to the smooth scrolling effect seen in MS Word 2013, but I haven't come across any other instances of this. I've heard that AJAX can make such th ...

Issue encountered when exporting with node and mongoose

After creating some schema and exporting the model, here is the code: var mongoose = require('mongoose'); var specSchema = new mongoose.Schema({ name: String, description:String }); var qualSchema = new mongoose.Schema({ name: Str ...

What is the best way to apply three unique classes to multiple div elements using jQuery?

Utilizing jQuery to assign three different classes to my div elements with the same name. Here is the HTML: <div class="main-class"> <div class="myclass"></div> <div class="myclass"></div> <div class="myclass"></div& ...

Exploring the universal scope in NodeJS Express for each request

I am working with a basic express server that is in need of storing global variables during request handling. Specifically, each request involves multiple operations that require information to be stored in a variable like global.transaction[]. However, u ...

Properly implementing prototypal inheritance: best practices

While there are numerous discussions on prototypal inheritance in JavaScript already, I assure you this is not just another lazy copy. Having thoroughly read all existing threads, I've noticed a plethora of syntactic approaches and varying answers whi ...

What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows: [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyNa ...