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=".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>
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./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!
Share Improve this question asked May 27, 2020 at 10:13 GitPHPGitPHP 31 silver badge2 bronze badges 1-
1
Just using plain HTML: <input type="number"> will limit to numbers, and the
pattern
attribute can be used to specify a regex suitable for the name field. – GKFX Commented May 27, 2020 at 10:18
1 Answer
Reset to default 7There 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 puted 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: ""
}),
puted: {
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