Creating a Custom Input Validator for Alphanumeric Values in Vue.js: To allow only alphabets and numbers in Vue.js, you can use a regular expression pattern to validate input in a form or input field. This can be achieved by adding a custom validator to the input field. The regular expression pattern can be set to allow only alphabets and numbers by using the characters A-Z (both upper and lower case) and 0-9. The pattern can then be tested against the input value using the test() method. If the input value matches the pattern, the validator will return true and the input will be considered valid. If the input value does not match the pattern, the validator will return an error message and the input will be considered invalid.
How to accept only alphabets and numbers in input field in Vue Js?
- The HTML code defines a form with an input field and a paragraph element. The input field has two Vue directives applied to it:
v-modelandv-bind:value. - The
v-modeldirective sets up two-way data binding between the input field and a Vue data property calledinputValue. This means that any changes to the input field will automatically update theinputValueproperty, and vice versa. - The
v-bind:valuedirective sets the initial value of the input field to the computed propertycleanInputValue. This means that the input field will display the cleaned version of the user’s input. - The
pelement is set up to only display if theinputValidproperty is false. This will only occur if the user’s input contains any characters that are not letters or numbers. - The
datamethod is used to define the initial state of the Vue instance. In this case, it setsinputValueto an empty string andinputValidto true. - The
computedproperty defines a new property calledcleanInputValue. This property takes the user’s input frominputValueand uses a regular expression to remove any characters that are not letters or numbers. The method then updates theinputValidproperty to indicate whether the user’s input was valid or not, and returns the cleaned version of the input.
Vue.js Form Input Validation for Alphanumeric Characters
<div id="app">
<input type="text" v-model="inputValue" v-bind:value="cleanInputValue">
<p v-if="!inputValid" style="color: red;">Input can only contain letters and numbers</p>
</div>
<script type="module">
const app = Vue.createApp({
el: "#app",
data() {
return {
inputValue: '',
inputValid: true
};
},
computed: {
cleanInputValue() {
const cleanedValue = this.inputValue.replace(/[^a-zA-Z0-9]/g, '');
this.inputValid = cleanedValue === this.inputValue;
return cleanedValue;
}
},
})
app.mount("#app")
</script>
Output of above example



