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:
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?
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