What is the best way to use a regex to filter the user's input in a Vuetify combobox and generate a chip?

I am working on implementing a restriction for a specific regex pattern while the user types in a combobox to add new chips, such as allowing only phone number chips.

<template>
  <v-container>
    <v-row>
      <v-col>
        <v-combobox
          v-model="chips"
          chips
          :delimiters="[',']"
          append-icon=""
          clearable
          hint="Hey I'm a 🥔 hint!"
          persistent-hint
          label="Type your favorite 🥔s"
          multiple
          solo
          @input="meowInput"
          @change="meowInput"
        >
          <template v-slot:selection="{ attrs, item }">
            <v-chip
              v-bind="attrs"
              close
              :color="getColor(item)"
              @click:close="remove(item)"
            >
              <strong>🥔{{ item }}</strong
              >&nbsp;
            </v-chip>
          </template>
        </v-combobox>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import ColorHash from "color-hash";

export default {
  name: "Experimental",
  components: {},
  data() {
    return {
      select: [],
      chips: [],
      search: "", //sync search
    };
  },
  methods: {
    meowInput(e) {
      console.log(e);
    },
    getColor(item) {
      const colorHash = new ColorHash({ lightness: 0.9 });
      return colorHash.hex(item);
    },
    remove(item) {
      this.chips.splice(this.chips.indexOf(item), 1);
      this.chips = [...this.chips];
    },
  },
};
</script>

Any suggestions on how to achieve this behavior?

Answer â„–1

To make this work effectively, I suggest using a regular expression to validate the input (in this case, I used US phone numbers as an example, but you can customize it for your needs). If the input does not pass the regex test, simply remove the value from the chips array.

Check out the code snippet below for a better understanding:


    <template>
      <v-container>
        // Your code goes here
      </v-container>
    </template>

    <script>
    import ColorHash from "color-hash";

    export default {
      name: "ValidationComponent",
      components: {},
      data() {
        return {
          select: [],
          chips: [],
          search: "", //sync search
        };
      },
      methods: {
        handleInput(e) {
          if (!/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/.test(e)) {
            console.log("Invalid input!");
            console.log(this.chips);
            this.chips.pop();
          } else {
            console.log("Valid phone number");
          }
        },
        getColor(item) {
          const colorHash = new ColorHash({ lightness: 0.9 });
          return colorHash.hex(item);
        },
        remove(item) {
          this.chips.splice(this.chips.indexOf(item), 1);
          this.chips = [...this.chips];
        },
      },
    };
    </script>

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

Which is more efficient: Implementing caching on the frontend or on the

Currently, I am using ajax to send requests to the backend server, where operations are performed and responses are received: function getData() { new Ajax().getResponse() .then(function (response) { // handle response }) .catch(functi ...

AngularJS: iterating through POST requests and passing each index into its corresponding response

Using AngularJS, I am attempting to execute multiple http POST requests and create an object of successfully finished requests. Here is a sample code snippet: var params = [1, 2, 3], url, i, done = {}; for (i in params) { url = '/dir ...

Eliminate HTML nodes that are not currently visible

I am currently developing a Vue/Vuetify application that showcases a large number of images (10-20k) in a grid view along with some additional information. These images are grouped into different sections, and clicking on an image opens an overlay displayi ...

Unable to assign image src to a dynamically generated div

My current task involves setting the background URL of a dynamically created div in JavaScript, intended for use with the jQuery Orbit slider. Below is my approach: var content1 = null; $("#featured").html("<div id='content' style='&apos ...

The VLC WebPlugin puts a halt on websocket activity during playback

I currently have a basic HTML/JS application that includes an embedded VLC WebPlugin and several methods for play/pause functionality. This application is being managed by another JavaScript file through a straightforward server/websocket C# setup. The con ...

The program encountered an error while trying to access the undefined property '_header'

An issue arises when the app.use(express.static("web")) line is executed. var express = require('express')(); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); //app.get(&apo ...

What changes will be brought about by switching from createWebHashHistory() to createWebHistory()?

I recently launched an application that utilizes createWebHashHistory() to handle URLs. One example is when a user visits this URL to access the earthquakes channel: https://app.radar.chat/#/channel/earthquakes Now, I am considering transitioning to using ...

When using Mongoose and Socket.IO, an empty string will not be printed if the result is empty

I'm facing an issue with a filter I created using socket.io and mongoose. Specifically, I'm trying to display a message if there are no results returned when querying, but it seems to not be working as expected. Restaurant.find({ $text : { $sear ...

AngularJS application: the button requires two clicks to activate

In my attempt to develop a simple CRUD app using AngularJS, I encountered an issue. The initial step involves clicking a button that fetches data from a REST API and populates an array. This array is then iterated using ng-repeat to generate Bootstrap card ...

Use JavaScript to find any text enclosed within [quote] and [/quote] tags and then replace it with <div class="quote-text">foo text</div>

Hey there! I have a specific text format that looks like this: [quote]foo text[/quote] and I would like to convert it to the following: <div class="quote-text">foo text</div> Do you have any idea how I can achieve this using JavaScript? Cu ...

How can images from a dynamic table be converted to base64 format in Vue.js and then sent in a JSON file?

Hello everyone, I'm facing an issue with a dynamic table where I need to add multiple rows, each containing a different image. I attempted to convert these images to base64 format and save them in a JSON file along with the table data. However, the pr ...

How can I customize the <span> element created by material-ui?

Is there a way I can customize the appearance of the <span> tag that is produced when using the Checkbox component from the material-ui library? Essentially, I am seeking a method to alter: <span class="MuiButtonBase-root-29 MuiIconButton-root-2 ...

Encountered an unexpected token '{' error in Discord.js and Node.js integration

let user = message.mentions.users.first(); if (message.mentions.users.size < 1) return message.reply('Please mention someone to issue ARs.').catch(console.error); mcash[${user.id}, ${message.guild.id}].mc ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

I must convert this option into a checkbox

I am facing a challenge with this task, where I need to convert a select form into a checkbox form. Although I have managed to change the visuals, the functionality of the checkboxes does not match that of the select form. Below is the original select for ...

Error: foobar is not defined within this scope (anonymous function)

I'm facing an issue with a JavaScript file hosted on a domain called foobar.com. at http://foobar.com/static/js/main.js: $(document).ready(function() { function foobar(bar){ $.ajax({ url: "/site/foo/", ...

Trying to understand the strange behavior of HTML parsing with jQuery in Javascript and Firefox

I have been working on a script to parse an HTML page using jQuery. The script runs smoothly in Chrome, IE, and Safari, but I'm facing some unexpected behavior while testing it in Firefox (version 36.0.1). Here's the code snippet: $.ajax({ u ...

Is it better to use AngularJS' ngMock inject before each test or for each individual test case?

Current Situation As I work on writing tests for an Angular project, I have come across a common practice of creating "global" variables in a describe block to store dependencies needed for the tests. This approach involves defining variables like $contro ...

What causes my absolutely positioned element to disappear when using overflow-x: hidden?

I've been experimenting with the CSS property overflow-x: hidden on a container and noticed that it causes my element with position: absolute to disappear. To see this effect in action, check out this demo: https://codepen.io/Karina1703/pen/LYMzqEj ...

Express-Session Object Method

I am currently facing an issue with linking an object to an Express session. Below is the code I am using: var express = require('express'); var session = require('express-session'); // Defining an object named "engine" which simulate ...