简体   繁体   中英

How can I allow only numbers and letters on Vue Js?

I want on the field name allow only numbers and letters and on the field number only allow numbers.

How I should do it, where can I see a doc where explain it, like my question?

 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>

Thanks!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM