[Vuejs]-How can I allow only numbers and letters on Vue Js?

7👍

There are few ways to do this, you can listen to keypress event on the input then check whether the key is letter or number using regex

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

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

or you can use computed properties to check whether a the input value is letter or number only or not, with this way, user can still type anything other than number and letter, but it will shows error

<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: () => ({
    name: ""
  }),
  computed: {
    nameValid() {
      return /^[A-Za-z0-9]+$/.test(this.name);
    }
  }
};
</script>

Example here: https://codesandbox.io/s/cranky-meadow-0dns8?file=/src/App.vue:0-651

👤Owl

Leave a comment