Validating Names in Vue.js

I need to create a form input field for a person's name. How can I make sure that only alphabets are allowed and numbers are not permitted?


<div>
<input type="text" class="from-input" placeholder="Enter Your Name..." v-model="name" />
<span v-if="this.name == ''">Please enter your name</span>
<span v-else-if="this.nameValidation">Only alphabets are allowed, no numbers allowed</span>
</div>

data(){
  return {
     name: "",
  }
}

computed: {
  nameValidation(){
        if(/^[a-zA-Z]+(?:-[a-zA-Z]+)*$/.test(this.name)){
            return true
        }else{
            false
        }
   }
}

Answer №1

Implement the HTML5 pattern attribute for input validation.

<input 
  type="email" 
  class="user-email"
  placeholder="Your Email Address..."
  v-model="email" 
  pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"/>

Answer №2

Utilizing the native input 'pattern' property is a more straightforward approach. However, if you prefer to solely rely on Vue for this functionality, you can implement the following solution:

new Vue({
  el: '#app',
  components: {
  comp: {
      data() {
      return{
        input: '',
          error: ''
        }
      },
      template: `
        <div>
          <input type="text" @keyup="checkValue" v-model="input" />
          <div v-if="error" class="alert">{{ error }}</div>
        </div>
      `,
      methods: {
      checkValue(){
           if(/[^a-zA-Z]/.test(this.input)) {
           this.error = 'Input value contains other syntax.';
           }else{
              this.error = '';
           }
        }
      }
    }
  }
})
input{
    display: block;
    margin-bottom: 5px;
    padding: 5px;
    border-radius: 4px;
    border: 1px solid #b3b3b3;
}

.alert{
      padding: 5px 10px;
    border: 1px solid #ff72728a;
    display: inline-block;
    color: #d48888;
    border-radius: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <comp></comp>
</div>

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

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

What is the best way to verify changing input fields in vue.js?

Validation of input fields using vuelidate is essential. The input field in question is dynamic, as the value is populated dynamically with jsonData through the use of v-model. The objective: Upon blur, the goal is to display an error if there is one; ho ...

Testing Vue Components - Simulating the return value of a plugin

I have a unique scenario where I need to mock the return value of a custom plugin without importing it directly into my test. By creating a mock function for the plugin, I can easily achieve this goal. However, I am unsure how to change the return value of ...

Exploring solutions for handling asynchronous issues with vue3-google-map

While working with a Vue library for managing Maps called vue3-google-map, I encountered an issue when trying to define certain polylines that would not allow me to select the center of the marked area: Here is my map template: <template> <Goo ...

Look into the data with vue.js, but there's not much

1. As a newcomer to vue.js, I encountered some surprising issues while experimenting with examples. The first one arose when I assigned an id to the body tag and included the following JavaScript code: <html> <head> <meta charset="utf-8 ...

Flatten information from an object containing multiple objects within an array

In my current project using Vue, I am making an API call to retrieve data from my Laravel backend (nova). The returned data is structured in the following way. The data consists of an array, which contains arrays of objects. Each array represents a record ...

Is there a way for me to retrieve props that have been passed through the Vue router within a Vue component?

I have configured a route as shown below: { path: 'fit-details', name: 'fit-details', component: Fitment, props: true }, I am passing props via the route using data from the state: this.$router.push({ path: 'fit-details&a ...

Having trouble getting a JS file to work with the Laravel Inertia.js and Vue.js3 template

Just getting started with inertia.js and facing an issue. My CSS styles are being applied, but my JavaScript file isn't functioning as expected. I'm working on an admin dashboard using Laravel 9 and vue.js-3 with a custom HTML template. Interes ...

When trying to locate an item in an array within a VUE application, it may result in

I've got this code snippet that successfully finds the item details in an array: var findGroupId = medias.find(medias => medias.group_name === this.groupName) The medias variable is an array. When I run console.log(findGroupId), I get this result ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

Exploring the attributes of cycled values in Vue.js

Currently, I am iterating over a list as shown below: <li v-for="item in filteredParentItems" v-if="item.action === 'list'" v-on:click="getNextPath" v-bind:data-next-path="item.nextPath" v-bind:data-action="item.action ...

The chosen option in the q-select is extending beyond the boundaries of the input field

Here's the code snippet I used for the q-select element: <q-select square outlined fill-input standout="bg-grey-3 text-white" v-model="unit_selection" :options="units&qu ...

Tips for prioritizing new data input at the top of the list

Hey there, I'm having trouble figuring out how to push new data to the top of a list using vue.js and laravel. I've been trying but haven't had any luck so far. If anyone could lend a hand, I would greatly appreciate it. Below is my Control ...

What are the reasons behind the pagination with numbers not functioning properly in Vue?

I've encountered an issue with my Vue application using Vuex while implementing pagination. The problem lies in the fact that the events stored are not being displayed, and neither are the page numbers for pagination. Another issue is that the paginat ...

Guide on utilizing map function in JavaScript and Vue to generate a fresh array

I am working on implementing a map method in JavaScript and Vue to generate a new array of objects while only including specific items in each object. I have designed a user interface with 2 checkboxes corresponding to 2 distinct objects: <div v-for ...

Parent-Child Communication in VueJS 2.0: How to effectively pass data from the parent component

Does anyone know a straightforward solution to this issue? I've been struggling to find one. Within my HTML file, there's a button that looks like this: <button @click="showModal">Show Modal</button> By clicking on the button, it t ...

What is the best way to determine which watchers are triggered in Vue.js?

Within my parent component, there are numerous nested child components. Whenever a click occurs on one of the child components, it triggers an update to the route. The parent component watches the route property and performs certain actions when it change ...

What is the best way to incorporate a vanilla javascript function into a vue.js application?

Consider a vanilla JavaScript function like this: if (window.devicePixelRatio >= 2) { document.querySelectorAll('img.retina').forEach(function (e) { let parts = e.src.split('.'); let ext = parts.pop(); i ...

Having difficulty accessing a public array item within chained AXIO transactions in VUE

I am currently facing an issue with a chained AXIOS call that is triggered from an array. The challenge I am encountering is ensuring that the second call completes before the first one initiates another API request, which seems to be working fine so far. ...

How can I interact with a v-dialog component within a child component in Vue.js using Vuetify?

Exploring Vue.js for the first time and hoping to display a login dialog upon button click. To maintain cleanliness in my code, I shifted the dialog to a child component within a parent component with nested LoginDialog. Below are snippets of the parent co ...