Search code examples
javascriptregexvue.jsvuetify.jsspecial-characters

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


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' 
  class="required"
  v-model='company_name'
  :rules="userNameRule">
</v-text-field>

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

Solution

  • 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/nightly@3.1.3-next-20230128.0/dist/vuetify.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/@vuetify/nightly@3.1.3-next-20230128.0/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>