Search code examples
validationvue.jsinputfiltervue-component

Vue.js – How to allow an user to type only letters in an input field?


I have an input field, let's call it firstName. I want to let an user to type only letters and apostrophes. No numbers and other special symbols. The logic is something like that:

  1. On @keydown some method (let's call it "checkName()") gets a typed character.
  2. Then it checks this symbol if it's belongs to something like [A-z]. If belongs, the method does nothing. If not – the method replaces it with ''. (Also need to add an apostrophe to this checking array to let an user to type it too).

How can I realize that? I've looked for a few Vue validators and masks, but haven't found there anything I need. Validators just check an input field, masks suite better, but it's necessary to have a fixed range of string.

Any ideas? Or maybe it's everything much easier and I make it complicated?


Solution

  • If you want the user only can type letters, then you can do v-on:keypress and check on the event function.

    <input type="text" v-model="firstName" v-on:keypress="isLetter($event)">
    

    then the method:

    isLetter(e) {
      let char = String.fromCharCode(e.keyCode); // Get the character
      if(/^[A-Za-z]+$/.test(char)) return true; // Match with regex 
      else e.preventDefault(); // If not match, don't add to input text
    }
    

    Example here: https://codesandbox.io/s/festive-buck-hm4fd?file=/src/App.vue

    You can change the regex pattern to ^[A-Za-z\']+$ if you also want to allow apostrophe

    I also added computed properties to check if the input value is valid or no in case you still want to allow users to input other than letters and shows error