Home > OS >  How to restrict special characters but allow alphabets, numbers and space in v-text-field vuetify
How to restrict special characters but allow alphabets, numbers and space in v-text-field vuetify

Time:01-29

Below is the text field for the company name. I don’t want to allow any special characters but I want to allow alphabets, space, and numbers. I am not sure how this can be achieved in vuetify. Any help to resolve this issue?

<v-text-field required
  label='Name' 
  
  v-model='company_name'
  :rules="userNameRule">
</v-text-field>

userNameRule: [
 value => !!value || 'Please enter company name'
]

CodePudding user response:

You can use v-form to trigger validation of the rule and use a regex for the rule.

<template>
  <v-app>
    <v-main>
      <v-form ref="form">
        <v-text-field required label='Name'  v-model='company_name' :rules="userNameRule" />
        </v-form>
    </v-main>
  </v-app>
</template>

<script setup>
import { ref, watch } from 'vue';

const userNameRule = [
  (v) => /^[a-zA-Z0-9 ] $/.test(v) || 'Name must be alphanumeric',
];
const company_name = ref('');
const form = ref(null);

watch(company_name, () => {
  form.value.validate();
});
</script>

https://vuetifyjs.com/en/components/forms/#props

CodePudding user response:

As per my understanding, You want to apply multiple validations on your company name input field.

  • Required field validation
  • Name must only contain alphabets, numeric and space.

If Yes, You can achieve the pattern validation using RegEx.

^[\w\s] $ Explanation :

^ - The beginning of a line, matches the characters defined inside the [] at the start of a line.
\w - means any word character, which usually means alphanumeric (letters, numbers, regardless of case) plus underscore (_)
\s - matches whitespace character.
[] - A character class, which means match any character contained in the character class.
- matches one or more occurrences of the character defined inside the [].
$ - matches the end

Here is the live demo :

const { createApp } = Vue
const { createVuetify } = Vuetify

const vuetify = createVuetify()

const app = createApp({
  template: '#app-template',
  data() {
    return {
      company_name: ''
    }
  }
}).use(vuetify).mount('#app')
<script src="https://unpkg.com/vue@next/dist/vue.global.js"></script>
<script src="https://unpkg.com/@vuetify/[email protected]/dist/vuetify.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@vuetify/[email protected]/dist/vuetify.css"/>

<script type="text/x-template" id="app-template">
      <v-text-field
        :rules="[
          v => !!v || 'Field is required',
          v => /^[\w\s] $/.test(v) || 'Name must only contain alphabets, numeric and space'      
        ]"
        label='Name'
        v-model='company_name'
      ></v-text-field>
</script>

<div id="app"></div>

  • Related