What is the best way to restrict input to only numbers and letters in Vue Js?

I only want the field name to accept numbers and letters, while the field number should only allow numbers.

How can I achieve this? Where can I find documentation that explains it clearly?

const app = new Vue({
  el: '#app',
  data: {
    name: null,
    number: null
  },
  methods: {
    checkForm: function (e) {
      if (this.name) {
        return true;
      }
      if (!this.name) {
        console.log("Required");
      }
      if (this.number) {
        return true;
      }
      if (!this.number) {
        console.log("Required");
      }
      e.preventDefault();
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<form id="app" @submit="checkForm" method="post" novalidate="true">
  <p>
    <label for="name">Name</label>
    <input id="name" v-model="name" type="text" name="name">
    <input id="number" v-model="number" type="text" name="number">
  </p>
  <input type="submit" value="Submit">
</form>

Many thanks!

Answer №1

One method to achieve this is by listening to the keypress event on the input field and then using regex to determine if the pressed key is a letter or number

<template>
  <div id="app">
    Text & Number Only
    <input type="text" v-model="name" v-on:keypress="isLetterOrNumber($event)">
  </div>
</template>

<script>
export default {
    data() {
        return {
            name: ""
        }
    },
    methods: {
        isLetterOrNumber(e) {
            let char = String.fromCharCode(e.keyCode);
            if (/^[A-Za-z0-9]+$/.test(char)) return true;
            else e.preventDefault();
        }
    }
}
</script>

Alternatively, computed properties can be used to validate whether the input contains only letters and numbers. In this approach, users can still input other characters but will be shown an error message

<template>
  <div id="app">
    Text & Number Only (show error):
    <input type="text" v-model="name">
    <div v-if="!nameValid">NOT VALID!!!</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: ""
    }
  },
  computed: {
    nameValid() {
      return /^[A-Za-z0-9]+$/.test(this.name);
    }
  }
};
</script>

For an example, you can refer to this sandbox link: https://codesandbox.io/s/cranky-meadow-0dns8?file=/src/App.vue:0-651

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

Compact looped slideshow

Currently in the process of designing a website and looking to incorporate a unique photo gallery feature. The concept is as follows: The photo gallery will be displayed in a rectangular/box shape. There are a total of 10 photos, with only 7 initially vis ...

Exploring the methods for interpreting a JSON object within a Vue.js framework

Here is the json object I am working with: const faqs = [{'question1':'answer1'},{'question2':'answer2'}] In my Vue.js code, I am attempting to iterate through this data using a for loop within a div like so: <di ...

Populate your HTML with JSON data

I need some guidance on how to achieve a specific task. I have a PHP file that retrieves data from a MySQL database and returns it in JSON format. Now, I want to display this data in HTML with "data_from_json" replaced by "18.5". Any assistance would be gr ...

Is it beneficial for performance to utilize JavaScript local variables intermittently?

Looking at these two sections of script, there is a slight difference in length and variable use. The first example is shorter by one line and uses one less variable $t, but it converts this into a jQuery object an extra time. Considering performance rath ...

Looking for assistance on how to automatically close the sidebar or pull navigation menu after clicking on a menu item

My website is designed to be responsive and includes a navigation slider that is hidden off-screen by default. The slider features a vertical push/pull bar that remains visible for users to access the menu. The entire navigation slider is fixed on the page ...

FIREBASE - ReferenceError: Authorization cannot be accessed until initialized

Currently, I am in the process of learning about Auth with Firebase using NextJS. I have been trying to grasp the concept by referring to multiple sources such as articles and YouTube videos, but I have encountered an error that is hindering my progress. ...

Angular 6 - Using properties in classes

Considering a component structured as follows: import { Component, OnInit, ViewChild } from '@angular/core'; @Component({ selector: '...', templateUrl: './...html', styleUrls: ['./...scss'] }) export class Te ...

What is the best way to modify a node_module file consisting of only a few exported variables, which is heavily utilized in the entire module? (with demonstration)

I have integrated a node module with the file structure displayed below. Inside the file node_core_ctx.js, I found this code snippet: const EventEmitter = require('events'); let sessions = new Map(); let publishers = new Map(); let idlePlayers ...

Sending Massive Real-Time Analytical Data

I am currently in the process of developing a dynamic analytics website using Asp.Net and C#. I am seeking advice on the most effective way to transmit data from the server to the client. Here are some options I have considered so far: Utilizing an Asp ...

Issue occurs when trying to access the 'set' property of an undefined variable, leading to an error message stating "Cannot read property 'set' of undefined" while using 'this

I'm facing an issue while setting up basic cookies for my Vue project. When I try to set a cookie, I encounter the following error. My package.json file indicates that I am using vue-cookies version ^1.7.4. The error message occurs when I click the bu ...

Why does Request-Body(req.body) display a value while Request-QueryParams(req.queryParams) returns null?

Using vuejs-axios, I successfully transferred client-side data to the server-side using Java with SparkJAVA Framework to manage the request-response cycle. The following code snippets demonstrate how Form-Data is posted from vuejs to java. const formData ...

Backbone "recalling" stored data in attributes

Presented here is a basic model: myTestModel = Backbone.Model.extend({ defaults: { title: 'My Title', config: {}, active: 1, } }) While nothing particularly stands out, there is an interesting observation regardi ...

Creating Javascript objects using provided JSON data

Good day! I am looking for assistance in understanding how to create objects from JSON data that has been provided: { "type":"FeatureCollection", "features":[ { "type":"Feature", ...

Get the content of a div element and paste it into an input field

Is there a way for me to copy text from a div with the same class name and input it into a designated field? I am attempting to extract text from the last div with the matching class name, and then paste it into an input field. How can I achieve this? ...

Working with real-time data in JavaScript to dynamically modify a JSON array

After making a request to an API, I receive a large JSON array. Using SignalR, I then obtain a smaller JSON array that only contains the objects from the API data that have been changed. My goal is to retrieve the modified objects from the API array and u ...

Smooth Slide Show Scrolling with Mouse Wheel Within a Container

My slick carousel with vertical scroll is causing issues as it scrolls the entire page. I am specifically looking to have it scroll within a particular div, such as the product section div. Any suggestions on how to achieve this? Html Code: <s ...

How to retrieve the path, route, or namespace of the current or parent component/view in a Vue.js application

I have been working on enhancing a sub-menu system for vue.js that dynamically populates based on the children routes of the current route. I recently asked a question about this and received a helpful answer. Currently, I am trying to further improve the ...

problem with accessing a website input area

Upon clicking outside the "subheader", I need to display the words "register" and "login" again, unless something is typed into the input fields... that's all there is to it, just click outside the subheader $(document).ready(function() { $(&ap ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...

Trouble with minification in Sencha cmd 5

I've been attempting to compress a Sencha 5 project using Sencha CMD, but I keep experiencing failures. sencha generate app -ext demoApp ./demoApp Then, in an effort to compress the application, I entered the following command: sencha app build ...